three.core.js 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '183dev';
  7. /**
  8. * Represents mouse buttons and interaction types in context of controls.
  9. *
  10. * @type {ConstantsMouse}
  11. * @constant
  12. */
  13. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  14. /**
  15. * Represents touch interaction types in context of controls.
  16. *
  17. * @type {ConstantsTouch}
  18. * @constant
  19. */
  20. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  21. /**
  22. * Disables face culling.
  23. *
  24. * @type {number}
  25. * @constant
  26. */
  27. const CullFaceNone = 0;
  28. /**
  29. * Culls back faces.
  30. *
  31. * @type {number}
  32. * @constant
  33. */
  34. const CullFaceBack = 1;
  35. /**
  36. * Culls front faces.
  37. *
  38. * @type {number}
  39. * @constant
  40. */
  41. const CullFaceFront = 2;
  42. /**
  43. * Culls both front and back faces.
  44. *
  45. * @type {number}
  46. * @constant
  47. */
  48. const CullFaceFrontBack = 3;
  49. /**
  50. * Gives unfiltered shadow maps - fastest, but lowest quality.
  51. *
  52. * @type {number}
  53. * @constant
  54. */
  55. const BasicShadowMap = 0;
  56. /**
  57. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm.
  58. *
  59. * @type {number}
  60. * @constant
  61. */
  62. const PCFShadowMap = 1;
  63. /**
  64. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm with
  65. * better soft shadows especially when using low-resolution shadow maps.
  66. *
  67. * @type {number}
  68. * @constant
  69. */
  70. const PCFSoftShadowMap = 2;
  71. /**
  72. * Filters shadow maps using the Variance Shadow Map (VSM) algorithm.
  73. * When using VSMShadowMap all shadow receivers will also cast shadows.
  74. *
  75. * @type {number}
  76. * @constant
  77. */
  78. const VSMShadowMap = 3;
  79. /**
  80. * Only front faces are rendered.
  81. *
  82. * @type {number}
  83. * @constant
  84. */
  85. const FrontSide = 0;
  86. /**
  87. * Only back faces are rendered.
  88. *
  89. * @type {number}
  90. * @constant
  91. */
  92. const BackSide = 1;
  93. /**
  94. * Both front and back faces are rendered.
  95. *
  96. * @type {number}
  97. * @constant
  98. */
  99. const DoubleSide = 2;
  100. /**
  101. * No blending is performed which effectively disables
  102. * alpha transparency.
  103. *
  104. * @type {number}
  105. * @constant
  106. */
  107. const NoBlending = 0;
  108. /**
  109. * The default blending.
  110. *
  111. * @type {number}
  112. * @constant
  113. */
  114. const NormalBlending = 1;
  115. /**
  116. * Represents additive blending.
  117. *
  118. * @type {number}
  119. * @constant
  120. */
  121. const AdditiveBlending = 2;
  122. /**
  123. * Represents subtractive blending.
  124. *
  125. * @type {number}
  126. * @constant
  127. */
  128. const SubtractiveBlending = 3;
  129. /**
  130. * Represents multiply blending.
  131. *
  132. * @type {number}
  133. * @constant
  134. */
  135. const MultiplyBlending = 4;
  136. /**
  137. * Represents custom blending.
  138. *
  139. * @type {number}
  140. * @constant
  141. */
  142. const CustomBlending = 5;
  143. /**
  144. * Represents material blending.
  145. *
  146. * @type {number}
  147. * @constant
  148. */
  149. const MaterialBlending = 6;
  150. /**
  151. * A `source + destination` blending equation.
  152. *
  153. * @type {number}
  154. * @constant
  155. */
  156. const AddEquation = 100;
  157. /**
  158. * A `source - destination` blending equation.
  159. *
  160. * @type {number}
  161. * @constant
  162. */
  163. const SubtractEquation = 101;
  164. /**
  165. * A `destination - source` blending equation.
  166. *
  167. * @type {number}
  168. * @constant
  169. */
  170. const ReverseSubtractEquation = 102;
  171. /**
  172. * A blend equation that uses the minimum of source and destination.
  173. *
  174. * @type {number}
  175. * @constant
  176. */
  177. const MinEquation = 103;
  178. /**
  179. * A blend equation that uses the maximum of source and destination.
  180. *
  181. * @type {number}
  182. * @constant
  183. */
  184. const MaxEquation = 104;
  185. /**
  186. * Multiplies all colors by `0`.
  187. *
  188. * @type {number}
  189. * @constant
  190. */
  191. const ZeroFactor = 200;
  192. /**
  193. * Multiplies all colors by `1`.
  194. *
  195. * @type {number}
  196. * @constant
  197. */
  198. const OneFactor = 201;
  199. /**
  200. * Multiplies all colors by the source colors.
  201. *
  202. * @type {number}
  203. * @constant
  204. */
  205. const SrcColorFactor = 202;
  206. /**
  207. * Multiplies all colors by `1` minus each source color.
  208. *
  209. * @type {number}
  210. * @constant
  211. */
  212. const OneMinusSrcColorFactor = 203;
  213. /**
  214. * Multiplies all colors by the source alpha value.
  215. *
  216. * @type {number}
  217. * @constant
  218. */
  219. const SrcAlphaFactor = 204;
  220. /**
  221. * Multiplies all colors by 1 minus the source alpha value.
  222. *
  223. * @type {number}
  224. * @constant
  225. */
  226. const OneMinusSrcAlphaFactor = 205;
  227. /**
  228. * Multiplies all colors by the destination alpha value.
  229. *
  230. * @type {number}
  231. * @constant
  232. */
  233. const DstAlphaFactor = 206;
  234. /**
  235. * Multiplies all colors by `1` minus the destination alpha value.
  236. *
  237. * @type {number}
  238. * @constant
  239. */
  240. const OneMinusDstAlphaFactor = 207;
  241. /**
  242. * Multiplies all colors by the destination color.
  243. *
  244. * @type {number}
  245. * @constant
  246. */
  247. const DstColorFactor = 208;
  248. /**
  249. * Multiplies all colors by `1` minus each destination color.
  250. *
  251. * @type {number}
  252. * @constant
  253. */
  254. const OneMinusDstColorFactor = 209;
  255. /**
  256. * Multiplies the RGB colors by the smaller of either the source alpha
  257. * value or the value of `1` minus the destination alpha value. The alpha
  258. * value is multiplied by `1`.
  259. *
  260. * @type {number}
  261. * @constant
  262. */
  263. const SrcAlphaSaturateFactor = 210;
  264. /**
  265. * Multiplies all colors by a constant color.
  266. *
  267. * @type {number}
  268. * @constant
  269. */
  270. const ConstantColorFactor = 211;
  271. /**
  272. * Multiplies all colors by `1` minus a constant color.
  273. *
  274. * @type {number}
  275. * @constant
  276. */
  277. const OneMinusConstantColorFactor = 212;
  278. /**
  279. * Multiplies all colors by a constant alpha value.
  280. *
  281. * @type {number}
  282. * @constant
  283. */
  284. const ConstantAlphaFactor = 213;
  285. /**
  286. * Multiplies all colors by 1 minus a constant alpha value.
  287. *
  288. * @type {number}
  289. * @constant
  290. */
  291. const OneMinusConstantAlphaFactor = 214;
  292. /**
  293. * Never pass.
  294. *
  295. * @type {number}
  296. * @constant
  297. */
  298. const NeverDepth = 0;
  299. /**
  300. * Always pass.
  301. *
  302. * @type {number}
  303. * @constant
  304. */
  305. const AlwaysDepth = 1;
  306. /**
  307. * Pass if the incoming value is less than the depth buffer value.
  308. *
  309. * @type {number}
  310. * @constant
  311. */
  312. const LessDepth = 2;
  313. /**
  314. * Pass if the incoming value is less than or equal to the depth buffer value.
  315. *
  316. * @type {number}
  317. * @constant
  318. */
  319. const LessEqualDepth = 3;
  320. /**
  321. * Pass if the incoming value equals the depth buffer value.
  322. *
  323. * @type {number}
  324. * @constant
  325. */
  326. const EqualDepth = 4;
  327. /**
  328. * Pass if the incoming value is greater than or equal to the depth buffer value.
  329. *
  330. * @type {number}
  331. * @constant
  332. */
  333. const GreaterEqualDepth = 5;
  334. /**
  335. * Pass if the incoming value is greater than the depth buffer value.
  336. *
  337. * @type {number}
  338. * @constant
  339. */
  340. const GreaterDepth = 6;
  341. /**
  342. * Pass if the incoming value is not equal to the depth buffer value.
  343. *
  344. * @type {number}
  345. * @constant
  346. */
  347. const NotEqualDepth = 7;
  348. /**
  349. * Multiplies the environment map color with the surface color.
  350. *
  351. * @type {number}
  352. * @constant
  353. */
  354. const MultiplyOperation = 0;
  355. /**
  356. * Uses reflectivity to blend between the two colors.
  357. *
  358. * @type {number}
  359. * @constant
  360. */
  361. const MixOperation = 1;
  362. /**
  363. * Adds the two colors.
  364. *
  365. * @type {number}
  366. * @constant
  367. */
  368. const AddOperation = 2;
  369. /**
  370. * No tone mapping is applied.
  371. *
  372. * @type {number}
  373. * @constant
  374. */
  375. const NoToneMapping = 0;
  376. /**
  377. * Linear tone mapping.
  378. *
  379. * @type {number}
  380. * @constant
  381. */
  382. const LinearToneMapping = 1;
  383. /**
  384. * Reinhard tone mapping.
  385. *
  386. * @type {number}
  387. * @constant
  388. */
  389. const ReinhardToneMapping = 2;
  390. /**
  391. * Cineon tone mapping.
  392. *
  393. * @type {number}
  394. * @constant
  395. */
  396. const CineonToneMapping = 3;
  397. /**
  398. * ACES Filmic tone mapping.
  399. *
  400. * @type {number}
  401. * @constant
  402. */
  403. const ACESFilmicToneMapping = 4;
  404. /**
  405. * Custom tone mapping.
  406. *
  407. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  408. *
  409. * @type {number}
  410. * @constant
  411. */
  412. const CustomToneMapping = 5;
  413. /**
  414. * AgX tone mapping.
  415. *
  416. * @type {number}
  417. * @constant
  418. */
  419. const AgXToneMapping = 6;
  420. /**
  421. * Neutral tone mapping.
  422. *
  423. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  424. *
  425. * @type {number}
  426. * @constant
  427. */
  428. const NeutralToneMapping = 7;
  429. /**
  430. * The skinned mesh shares the same world space as the skeleton.
  431. *
  432. * @type {string}
  433. * @constant
  434. */
  435. const AttachedBindMode = 'attached';
  436. /**
  437. * The skinned mesh does not share the same world space as the skeleton.
  438. * This is useful when a skeleton is shared across multiple skinned meshes.
  439. *
  440. * @type {string}
  441. * @constant
  442. */
  443. const DetachedBindMode = 'detached';
  444. /**
  445. * Maps textures using the geometry's UV coordinates.
  446. *
  447. * @type {number}
  448. * @constant
  449. */
  450. const UVMapping = 300;
  451. /**
  452. * Reflection mapping for cube textures.
  453. *
  454. * @type {number}
  455. * @constant
  456. */
  457. const CubeReflectionMapping = 301;
  458. /**
  459. * Refraction mapping for cube textures.
  460. *
  461. * @type {number}
  462. * @constant
  463. */
  464. const CubeRefractionMapping = 302;
  465. /**
  466. * Reflection mapping for equirectangular textures.
  467. *
  468. * @type {number}
  469. * @constant
  470. */
  471. const EquirectangularReflectionMapping = 303;
  472. /**
  473. * Refraction mapping for equirectangular textures.
  474. *
  475. * @type {number}
  476. * @constant
  477. */
  478. const EquirectangularRefractionMapping = 304;
  479. /**
  480. * Reflection mapping for PMREM textures.
  481. *
  482. * @type {number}
  483. * @constant
  484. */
  485. const CubeUVReflectionMapping = 306;
  486. /**
  487. * The texture will simply repeat to infinity.
  488. *
  489. * @type {number}
  490. * @constant
  491. */
  492. const RepeatWrapping = 1000;
  493. /**
  494. * The last pixel of the texture stretches to the edge of the mesh.
  495. *
  496. * @type {number}
  497. * @constant
  498. */
  499. const ClampToEdgeWrapping = 1001;
  500. /**
  501. * The texture will repeats to infinity, mirroring on each repeat.
  502. *
  503. * @type {number}
  504. * @constant
  505. */
  506. const MirroredRepeatWrapping = 1002;
  507. /**
  508. * Returns the value of the texture element that is nearest (in Manhattan distance)
  509. * to the specified texture coordinates.
  510. *
  511. * @type {number}
  512. * @constant
  513. */
  514. const NearestFilter = 1003;
  515. /**
  516. * Chooses the mipmap that most closely matches the size of the pixel being textured
  517. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  518. * to produce a texture value.
  519. *
  520. * @type {number}
  521. * @constant
  522. */
  523. const NearestMipmapNearestFilter = 1004;
  524. const NearestMipMapNearestFilter = 1004; // legacy
  525. /**
  526. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  527. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  528. * The final texture value is a weighted average of those two values.
  529. *
  530. * @type {number}
  531. * @constant
  532. */
  533. const NearestMipmapLinearFilter = 1005;
  534. const NearestMipMapLinearFilter = 1005; // legacy
  535. /**
  536. * Returns the weighted average of the four texture elements that are closest to the specified
  537. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  538. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  539. *
  540. * @type {number}
  541. * @constant
  542. */
  543. const LinearFilter = 1006;
  544. /**
  545. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  546. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  547. * center of the pixel) to produce a texture value.
  548. *
  549. * @type {number}
  550. * @constant
  551. */
  552. const LinearMipmapNearestFilter = 1007;
  553. const LinearMipMapNearestFilter = 1007; // legacy
  554. /**
  555. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  556. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  557. * is a weighted average of those two values.
  558. *
  559. * @type {number}
  560. * @constant
  561. */
  562. const LinearMipmapLinearFilter = 1008;
  563. const LinearMipMapLinearFilter = 1008; // legacy
  564. /**
  565. * An unsigned byte data type for textures.
  566. *
  567. * @type {number}
  568. * @constant
  569. */
  570. const UnsignedByteType = 1009;
  571. /**
  572. * A byte data type for textures.
  573. *
  574. * @type {number}
  575. * @constant
  576. */
  577. const ByteType = 1010;
  578. /**
  579. * A short data type for textures.
  580. *
  581. * @type {number}
  582. * @constant
  583. */
  584. const ShortType = 1011;
  585. /**
  586. * An unsigned short data type for textures.
  587. *
  588. * @type {number}
  589. * @constant
  590. */
  591. const UnsignedShortType = 1012;
  592. /**
  593. * An int data type for textures.
  594. *
  595. * @type {number}
  596. * @constant
  597. */
  598. const IntType = 1013;
  599. /**
  600. * An unsigned int data type for textures.
  601. *
  602. * @type {number}
  603. * @constant
  604. */
  605. const UnsignedIntType = 1014;
  606. /**
  607. * A float data type for textures.
  608. *
  609. * @type {number}
  610. * @constant
  611. */
  612. const FloatType = 1015;
  613. /**
  614. * A half float data type for textures.
  615. *
  616. * @type {number}
  617. * @constant
  618. */
  619. const HalfFloatType = 1016;
  620. /**
  621. * An unsigned short 4_4_4_4 (packed) data type for textures.
  622. *
  623. * @type {number}
  624. * @constant
  625. */
  626. const UnsignedShort4444Type = 1017;
  627. /**
  628. * An unsigned short 5_5_5_1 (packed) data type for textures.
  629. *
  630. * @type {number}
  631. * @constant
  632. */
  633. const UnsignedShort5551Type = 1018;
  634. /**
  635. * An unsigned int 24_8 data type for textures.
  636. *
  637. * @type {number}
  638. * @constant
  639. */
  640. const UnsignedInt248Type = 1020;
  641. /**
  642. * An unsigned int 5_9_9_9 (packed) data type for textures.
  643. *
  644. * @type {number}
  645. * @constant
  646. */
  647. const UnsignedInt5999Type = 35902;
  648. /**
  649. * An unsigned int 10_11_11 (packed) data type for textures.
  650. *
  651. * @type {number}
  652. * @constant
  653. */
  654. const UnsignedInt101111Type = 35899;
  655. /**
  656. * Discards the red, green and blue components and reads just the alpha component.
  657. *
  658. * @type {number}
  659. * @constant
  660. */
  661. const AlphaFormat = 1021;
  662. /**
  663. * Discards the alpha component and reads the red, green and blue component.
  664. *
  665. * @type {number}
  666. * @constant
  667. */
  668. const RGBFormat = 1022;
  669. /**
  670. * Reads the red, green, blue and alpha components.
  671. *
  672. * @type {number}
  673. * @constant
  674. */
  675. const RGBAFormat = 1023;
  676. /**
  677. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  678. *
  679. * @type {number}
  680. * @constant
  681. */
  682. const DepthFormat = 1026;
  683. /**
  684. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  685. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  686. *
  687. * @type {number}
  688. * @constant
  689. */
  690. const DepthStencilFormat = 1027;
  691. /**
  692. * Discards the green, blue and alpha components and reads just the red component.
  693. *
  694. * @type {number}
  695. * @constant
  696. */
  697. const RedFormat = 1028;
  698. /**
  699. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  700. *
  701. * @type {number}
  702. * @constant
  703. */
  704. const RedIntegerFormat = 1029;
  705. /**
  706. * Discards the alpha, and blue components and reads the red, and green components.
  707. *
  708. * @type {number}
  709. * @constant
  710. */
  711. const RGFormat = 1030;
  712. /**
  713. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  714. *
  715. * @type {number}
  716. * @constant
  717. */
  718. const RGIntegerFormat = 1031;
  719. /**
  720. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  721. *
  722. * @type {number}
  723. * @constant
  724. */
  725. const RGBIntegerFormat = 1032;
  726. /**
  727. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  728. *
  729. * @type {number}
  730. * @constant
  731. */
  732. const RGBAIntegerFormat = 1033;
  733. /**
  734. * A DXT1-compressed image in an RGB image format.
  735. *
  736. * @type {number}
  737. * @constant
  738. */
  739. const RGB_S3TC_DXT1_Format = 33776;
  740. /**
  741. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  742. *
  743. * @type {number}
  744. * @constant
  745. */
  746. const RGBA_S3TC_DXT1_Format = 33777;
  747. /**
  748. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  749. *
  750. * @type {number}
  751. * @constant
  752. */
  753. const RGBA_S3TC_DXT3_Format = 33778;
  754. /**
  755. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  756. * compression in how the alpha compression is done.
  757. *
  758. * @type {number}
  759. * @constant
  760. */
  761. const RGBA_S3TC_DXT5_Format = 33779;
  762. /**
  763. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  764. *
  765. * @type {number}
  766. * @constant
  767. */
  768. const RGB_PVRTC_4BPPV1_Format = 35840;
  769. /**
  770. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  771. *
  772. * @type {number}
  773. * @constant
  774. */
  775. const RGB_PVRTC_2BPPV1_Format = 35841;
  776. /**
  777. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  778. *
  779. * @type {number}
  780. * @constant
  781. */
  782. const RGBA_PVRTC_4BPPV1_Format = 35842;
  783. /**
  784. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  785. *
  786. * @type {number}
  787. * @constant
  788. */
  789. const RGBA_PVRTC_2BPPV1_Format = 35843;
  790. /**
  791. * ETC1 RGB format.
  792. *
  793. * @type {number}
  794. * @constant
  795. */
  796. const RGB_ETC1_Format = 36196;
  797. /**
  798. * ETC2 RGB format.
  799. *
  800. * @type {number}
  801. * @constant
  802. */
  803. const RGB_ETC2_Format = 37492;
  804. /**
  805. * ETC2 RGBA format.
  806. *
  807. * @type {number}
  808. * @constant
  809. */
  810. const RGBA_ETC2_EAC_Format = 37496;
  811. /**
  812. * EAC R11 UNORM format.
  813. *
  814. * @type {number}
  815. * @constant
  816. */
  817. const R11_EAC_Format = 37488; // 0x9270
  818. /**
  819. * EAC R11 SNORM format.
  820. *
  821. * @type {number}
  822. * @constant
  823. */
  824. const SIGNED_R11_EAC_Format = 37489; // 0x9271
  825. /**
  826. * EAC RG11 UNORM format.
  827. *
  828. * @type {number}
  829. * @constant
  830. */
  831. const RG11_EAC_Format = 37490; // 0x9272
  832. /**
  833. * EAC RG11 SNORM format.
  834. *
  835. * @type {number}
  836. * @constant
  837. */
  838. const SIGNED_RG11_EAC_Format = 37491; // 0x9273
  839. /**
  840. * ASTC RGBA 4x4 format.
  841. *
  842. * @type {number}
  843. * @constant
  844. */
  845. const RGBA_ASTC_4x4_Format = 37808;
  846. /**
  847. * ASTC RGBA 5x4 format.
  848. *
  849. * @type {number}
  850. * @constant
  851. */
  852. const RGBA_ASTC_5x4_Format = 37809;
  853. /**
  854. * ASTC RGBA 5x5 format.
  855. *
  856. * @type {number}
  857. * @constant
  858. */
  859. const RGBA_ASTC_5x5_Format = 37810;
  860. /**
  861. * ASTC RGBA 6x5 format.
  862. *
  863. * @type {number}
  864. * @constant
  865. */
  866. const RGBA_ASTC_6x5_Format = 37811;
  867. /**
  868. * ASTC RGBA 6x6 format.
  869. *
  870. * @type {number}
  871. * @constant
  872. */
  873. const RGBA_ASTC_6x6_Format = 37812;
  874. /**
  875. * ASTC RGBA 8x5 format.
  876. *
  877. * @type {number}
  878. * @constant
  879. */
  880. const RGBA_ASTC_8x5_Format = 37813;
  881. /**
  882. * ASTC RGBA 8x6 format.
  883. *
  884. * @type {number}
  885. * @constant
  886. */
  887. const RGBA_ASTC_8x6_Format = 37814;
  888. /**
  889. * ASTC RGBA 8x8 format.
  890. *
  891. * @type {number}
  892. * @constant
  893. */
  894. const RGBA_ASTC_8x8_Format = 37815;
  895. /**
  896. * ASTC RGBA 10x5 format.
  897. *
  898. * @type {number}
  899. * @constant
  900. */
  901. const RGBA_ASTC_10x5_Format = 37816;
  902. /**
  903. * ASTC RGBA 10x6 format.
  904. *
  905. * @type {number}
  906. * @constant
  907. */
  908. const RGBA_ASTC_10x6_Format = 37817;
  909. /**
  910. * ASTC RGBA 10x8 format.
  911. *
  912. * @type {number}
  913. * @constant
  914. */
  915. const RGBA_ASTC_10x8_Format = 37818;
  916. /**
  917. * ASTC RGBA 10x10 format.
  918. *
  919. * @type {number}
  920. * @constant
  921. */
  922. const RGBA_ASTC_10x10_Format = 37819;
  923. /**
  924. * ASTC RGBA 12x10 format.
  925. *
  926. * @type {number}
  927. * @constant
  928. */
  929. const RGBA_ASTC_12x10_Format = 37820;
  930. /**
  931. * ASTC RGBA 12x12 format.
  932. *
  933. * @type {number}
  934. * @constant
  935. */
  936. const RGBA_ASTC_12x12_Format = 37821;
  937. /**
  938. * BPTC RGBA format.
  939. *
  940. * @type {number}
  941. * @constant
  942. */
  943. const RGBA_BPTC_Format = 36492;
  944. /**
  945. * BPTC Signed RGB format.
  946. *
  947. * @type {number}
  948. * @constant
  949. */
  950. const RGB_BPTC_SIGNED_Format = 36494;
  951. /**
  952. * BPTC Unsigned RGB format.
  953. *
  954. * @type {number}
  955. * @constant
  956. */
  957. const RGB_BPTC_UNSIGNED_Format = 36495;
  958. /**
  959. * RGTC1 Red format.
  960. *
  961. * @type {number}
  962. * @constant
  963. */
  964. const RED_RGTC1_Format = 36283;
  965. /**
  966. * RGTC1 Signed Red format.
  967. *
  968. * @type {number}
  969. * @constant
  970. */
  971. const SIGNED_RED_RGTC1_Format = 36284;
  972. /**
  973. * RGTC2 Red Green format.
  974. *
  975. * @type {number}
  976. * @constant
  977. */
  978. const RED_GREEN_RGTC2_Format = 36285;
  979. /**
  980. * RGTC2 Signed Red Green format.
  981. *
  982. * @type {number}
  983. * @constant
  984. */
  985. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  986. /**
  987. * Animations are played once.
  988. *
  989. * @type {number}
  990. * @constant
  991. */
  992. const LoopOnce = 2200;
  993. /**
  994. * Animations are played with a chosen number of repetitions, each time jumping from
  995. * the end of the clip directly to its beginning.
  996. *
  997. * @type {number}
  998. * @constant
  999. */
  1000. const LoopRepeat = 2201;
  1001. /**
  1002. * Animations are played with a chosen number of repetitions, alternately playing forward
  1003. * and backward.
  1004. *
  1005. * @type {number}
  1006. * @constant
  1007. */
  1008. const LoopPingPong = 2202;
  1009. /**
  1010. * Discrete interpolation mode for keyframe tracks.
  1011. *
  1012. * @type {number}
  1013. * @constant
  1014. */
  1015. const InterpolateDiscrete = 2300;
  1016. /**
  1017. * Linear interpolation mode for keyframe tracks.
  1018. *
  1019. * @type {number}
  1020. * @constant
  1021. */
  1022. const InterpolateLinear = 2301;
  1023. /**
  1024. * Smooth interpolation mode for keyframe tracks.
  1025. *
  1026. * @type {number}
  1027. * @constant
  1028. */
  1029. const InterpolateSmooth = 2302;
  1030. /**
  1031. * Bezier interpolation mode for keyframe tracks.
  1032. *
  1033. * Uses cubic Bezier curves with explicit 2D control points.
  1034. * Requires tangent data to be set on the track.
  1035. *
  1036. * @type {number}
  1037. * @constant
  1038. */
  1039. const InterpolateBezier = 2303;
  1040. /**
  1041. * Zero curvature ending for animations.
  1042. *
  1043. * @type {number}
  1044. * @constant
  1045. */
  1046. const ZeroCurvatureEnding = 2400;
  1047. /**
  1048. * Zero slope ending for animations.
  1049. *
  1050. * @type {number}
  1051. * @constant
  1052. */
  1053. const ZeroSlopeEnding = 2401;
  1054. /**
  1055. * Wrap around ending for animations.
  1056. *
  1057. * @type {number}
  1058. * @constant
  1059. */
  1060. const WrapAroundEnding = 2402;
  1061. /**
  1062. * Default animation blend mode.
  1063. *
  1064. * @type {number}
  1065. * @constant
  1066. */
  1067. const NormalAnimationBlendMode = 2500;
  1068. /**
  1069. * Additive animation blend mode. Can be used to layer motions on top of
  1070. * each other to build complex performances from smaller re-usable assets.
  1071. *
  1072. * @type {number}
  1073. * @constant
  1074. */
  1075. const AdditiveAnimationBlendMode = 2501;
  1076. /**
  1077. * For every three vertices draw a single triangle.
  1078. *
  1079. * @type {number}
  1080. * @constant
  1081. */
  1082. const TrianglesDrawMode = 0;
  1083. /**
  1084. * For each vertex draw a triangle from the last three vertices.
  1085. *
  1086. * @type {number}
  1087. * @constant
  1088. */
  1089. const TriangleStripDrawMode = 1;
  1090. /**
  1091. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1092. *
  1093. * @type {number}
  1094. * @constant
  1095. */
  1096. const TriangleFanDrawMode = 2;
  1097. /**
  1098. * The depth value is inverted (1.0 - z) for visualization purposes.
  1099. *
  1100. * @type {number}
  1101. * @constant
  1102. */
  1103. const BasicDepthPacking = 3200;
  1104. /**
  1105. * The depth value is packed into 32 bit RGBA.
  1106. *
  1107. * @type {number}
  1108. * @constant
  1109. */
  1110. const RGBADepthPacking = 3201;
  1111. /**
  1112. * The depth value is packed into 24 bit RGB.
  1113. *
  1114. * @type {number}
  1115. * @constant
  1116. */
  1117. const RGBDepthPacking = 3202;
  1118. /**
  1119. * The depth value is packed into 16 bit RG.
  1120. *
  1121. * @type {number}
  1122. * @constant
  1123. */
  1124. const RGDepthPacking = 3203;
  1125. /**
  1126. * Normal information is relative to the underlying surface.
  1127. *
  1128. * @type {number}
  1129. * @constant
  1130. */
  1131. const TangentSpaceNormalMap = 0;
  1132. /**
  1133. * Normal information is relative to the object orientation.
  1134. *
  1135. * @type {number}
  1136. * @constant
  1137. */
  1138. const ObjectSpaceNormalMap = 1;
  1139. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1140. /**
  1141. * No color space.
  1142. *
  1143. * @type {string}
  1144. * @constant
  1145. */
  1146. const NoColorSpace = '';
  1147. /**
  1148. * sRGB color space.
  1149. *
  1150. * @type {string}
  1151. * @constant
  1152. */
  1153. const SRGBColorSpace = 'srgb';
  1154. /**
  1155. * sRGB-linear color space.
  1156. *
  1157. * @type {string}
  1158. * @constant
  1159. */
  1160. const LinearSRGBColorSpace = 'srgb-linear';
  1161. /**
  1162. * Linear transfer function.
  1163. *
  1164. * @type {string}
  1165. * @constant
  1166. */
  1167. const LinearTransfer = 'linear';
  1168. /**
  1169. * sRGB transfer function.
  1170. *
  1171. * @type {string}
  1172. * @constant
  1173. */
  1174. const SRGBTransfer = 'srgb';
  1175. /**
  1176. * No normal map packing.
  1177. *
  1178. * @type {string}
  1179. * @constant
  1180. */
  1181. const NoNormalPacking = '';
  1182. /**
  1183. * Normal RG packing.
  1184. *
  1185. * @type {string}
  1186. * @constant
  1187. */
  1188. const NormalRGPacking = 'rg';
  1189. /**
  1190. * Normal GA packing.
  1191. *
  1192. * @type {string}
  1193. * @constant
  1194. */
  1195. const NormalGAPacking = 'ga';
  1196. /**
  1197. * Sets the stencil buffer value to `0`.
  1198. *
  1199. * @type {number}
  1200. * @constant
  1201. */
  1202. const ZeroStencilOp = 0;
  1203. /**
  1204. * Keeps the current value.
  1205. *
  1206. * @type {number}
  1207. * @constant
  1208. */
  1209. const KeepStencilOp = 7680;
  1210. /**
  1211. * Sets the stencil buffer value to the specified reference value.
  1212. *
  1213. * @type {number}
  1214. * @constant
  1215. */
  1216. const ReplaceStencilOp = 7681;
  1217. /**
  1218. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1219. *
  1220. * @type {number}
  1221. * @constant
  1222. */
  1223. const IncrementStencilOp = 7682;
  1224. /**
  1225. * Decrements the current stencil buffer value. Clamps to `0`.
  1226. *
  1227. * @type {number}
  1228. * @constant
  1229. */
  1230. const DecrementStencilOp = 7683;
  1231. /**
  1232. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1233. * the maximum representable unsigned value.
  1234. *
  1235. * @type {number}
  1236. * @constant
  1237. */
  1238. const IncrementWrapStencilOp = 34055;
  1239. /**
  1240. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1241. * unsigned value when decrementing a stencil buffer value of `0`.
  1242. *
  1243. * @type {number}
  1244. * @constant
  1245. */
  1246. const DecrementWrapStencilOp = 34056;
  1247. /**
  1248. * Inverts the current stencil buffer value bitwise.
  1249. *
  1250. * @type {number}
  1251. * @constant
  1252. */
  1253. const InvertStencilOp = 5386;
  1254. /**
  1255. * Will never return true.
  1256. *
  1257. * @type {number}
  1258. * @constant
  1259. */
  1260. const NeverStencilFunc = 512;
  1261. /**
  1262. * Will return true if the stencil reference value is less than the current stencil value.
  1263. *
  1264. * @type {number}
  1265. * @constant
  1266. */
  1267. const LessStencilFunc = 513;
  1268. /**
  1269. * Will return true if the stencil reference value is equal to the current stencil value.
  1270. *
  1271. * @type {number}
  1272. * @constant
  1273. */
  1274. const EqualStencilFunc = 514;
  1275. /**
  1276. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1277. *
  1278. * @type {number}
  1279. * @constant
  1280. */
  1281. const LessEqualStencilFunc = 515;
  1282. /**
  1283. * Will return true if the stencil reference value is greater than the current stencil value.
  1284. *
  1285. * @type {number}
  1286. * @constant
  1287. */
  1288. const GreaterStencilFunc = 516;
  1289. /**
  1290. * Will return true if the stencil reference value is not equal to the current stencil value.
  1291. *
  1292. * @type {number}
  1293. * @constant
  1294. */
  1295. const NotEqualStencilFunc = 517;
  1296. /**
  1297. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1298. *
  1299. * @type {number}
  1300. * @constant
  1301. */
  1302. const GreaterEqualStencilFunc = 518;
  1303. /**
  1304. * Will always return true.
  1305. *
  1306. * @type {number}
  1307. * @constant
  1308. */
  1309. const AlwaysStencilFunc = 519;
  1310. /**
  1311. * Never pass.
  1312. *
  1313. * @type {number}
  1314. * @constant
  1315. */
  1316. const NeverCompare = 512;
  1317. /**
  1318. * Pass if the incoming value is less than the texture value.
  1319. *
  1320. * @type {number}
  1321. * @constant
  1322. */
  1323. const LessCompare = 513;
  1324. /**
  1325. * Pass if the incoming value equals the texture value.
  1326. *
  1327. * @type {number}
  1328. * @constant
  1329. */
  1330. const EqualCompare = 514;
  1331. /**
  1332. * Pass if the incoming value is less than or equal to the texture value.
  1333. *
  1334. * @type {number}
  1335. * @constant
  1336. */
  1337. const LessEqualCompare = 515;
  1338. /**
  1339. * Pass if the incoming value is greater than the texture value.
  1340. *
  1341. * @type {number}
  1342. * @constant
  1343. */
  1344. const GreaterCompare = 516;
  1345. /**
  1346. * Pass if the incoming value is not equal to the texture value.
  1347. *
  1348. * @type {number}
  1349. * @constant
  1350. */
  1351. const NotEqualCompare = 517;
  1352. /**
  1353. * Pass if the incoming value is greater than or equal to the texture value.
  1354. *
  1355. * @type {number}
  1356. * @constant
  1357. */
  1358. const GreaterEqualCompare = 518;
  1359. /**
  1360. * Always pass.
  1361. *
  1362. * @type {number}
  1363. * @constant
  1364. */
  1365. const AlwaysCompare = 519;
  1366. /**
  1367. * The contents are intended to be specified once by the application, and used many
  1368. * times as the source for drawing and image specification commands.
  1369. *
  1370. * @type {number}
  1371. * @constant
  1372. */
  1373. const StaticDrawUsage = 35044;
  1374. /**
  1375. * The contents are intended to be respecified repeatedly by the application, and
  1376. * used many times as the source for drawing and image specification commands.
  1377. *
  1378. * @type {number}
  1379. * @constant
  1380. */
  1381. const DynamicDrawUsage = 35048;
  1382. /**
  1383. * The contents are intended to be specified once by the application, and used at most
  1384. * a few times as the source for drawing and image specification commands.
  1385. *
  1386. * @type {number}
  1387. * @constant
  1388. */
  1389. const StreamDrawUsage = 35040;
  1390. /**
  1391. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1392. * many times by the application.
  1393. *
  1394. * @type {number}
  1395. * @constant
  1396. */
  1397. const StaticReadUsage = 35045;
  1398. /**
  1399. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1400. * many times by the application.
  1401. *
  1402. * @type {number}
  1403. * @constant
  1404. */
  1405. const DynamicReadUsage = 35049;
  1406. /**
  1407. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1408. * a few times by the application
  1409. *
  1410. * @type {number}
  1411. * @constant
  1412. */
  1413. const StreamReadUsage = 35041;
  1414. /**
  1415. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1416. * the source for WebGL drawing and image specification commands.
  1417. *
  1418. * @type {number}
  1419. * @constant
  1420. */
  1421. const StaticCopyUsage = 35046;
  1422. /**
  1423. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1424. * as the source for WebGL drawing and image specification commands.
  1425. *
  1426. * @type {number}
  1427. * @constant
  1428. */
  1429. const DynamicCopyUsage = 35050;
  1430. /**
  1431. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1432. * as the source for WebGL drawing and image specification commands.
  1433. *
  1434. * @type {number}
  1435. * @constant
  1436. */
  1437. const StreamCopyUsage = 35042;
  1438. /**
  1439. * GLSL 1 shader code.
  1440. *
  1441. * @type {string}
  1442. * @constant
  1443. */
  1444. const GLSL1 = '100';
  1445. /**
  1446. * GLSL 3 shader code.
  1447. *
  1448. * @type {string}
  1449. * @constant
  1450. */
  1451. const GLSL3 = '300 es';
  1452. /**
  1453. * WebGL coordinate system.
  1454. *
  1455. * @type {number}
  1456. * @constant
  1457. */
  1458. const WebGLCoordinateSystem = 2000;
  1459. /**
  1460. * WebGPU coordinate system.
  1461. *
  1462. * @type {number}
  1463. * @constant
  1464. */
  1465. const WebGPUCoordinateSystem = 2001;
  1466. /**
  1467. * Represents the different timestamp query types.
  1468. *
  1469. * @type {ConstantsTimestampQuery}
  1470. * @constant
  1471. */
  1472. const TimestampQuery = {
  1473. COMPUTE: 'compute',
  1474. RENDER: 'render'
  1475. };
  1476. /**
  1477. * Represents mouse buttons and interaction types in context of controls.
  1478. *
  1479. * @type {ConstantsInterpolationSamplingType}
  1480. * @constant
  1481. */
  1482. const InterpolationSamplingType = {
  1483. PERSPECTIVE: 'perspective',
  1484. LINEAR: 'linear',
  1485. FLAT: 'flat'
  1486. };
  1487. /**
  1488. * Represents the different interpolation sampling modes.
  1489. *
  1490. * @type {ConstantsInterpolationSamplingMode}
  1491. * @constant
  1492. */
  1493. const InterpolationSamplingMode = {
  1494. NORMAL: 'normal',
  1495. CENTROID: 'centroid',
  1496. SAMPLE: 'sample',
  1497. FIRST: 'first',
  1498. EITHER: 'either'
  1499. };
  1500. /**
  1501. * Compatibility flags for features that may not be supported across all platforms.
  1502. *
  1503. * @type {Object}
  1504. * @constant
  1505. */
  1506. const Compatibility = {
  1507. TEXTURE_COMPARE: 'depthTextureCompare'
  1508. };
  1509. /**
  1510. * This type represents mouse buttons and interaction types in context of controls.
  1511. *
  1512. * @typedef {Object} ConstantsMouse
  1513. * @property {number} MIDDLE - The left mouse button.
  1514. * @property {number} LEFT - The middle mouse button.
  1515. * @property {number} RIGHT - The right mouse button.
  1516. * @property {number} ROTATE - A rotate interaction.
  1517. * @property {number} DOLLY - A dolly interaction.
  1518. * @property {number} PAN - A pan interaction.
  1519. **/
  1520. /**
  1521. * This type represents touch interaction types in context of controls.
  1522. *
  1523. * @typedef {Object} ConstantsTouch
  1524. * @property {number} ROTATE - A rotate interaction.
  1525. * @property {number} PAN - A pan interaction.
  1526. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1527. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1528. **/
  1529. /**
  1530. * This type represents the different timestamp query types.
  1531. *
  1532. * @typedef {Object} ConstantsTimestampQuery
  1533. * @property {string} COMPUTE - A `compute` timestamp query.
  1534. * @property {string} RENDER - A `render` timestamp query.
  1535. **/
  1536. /**
  1537. * Represents the different interpolation sampling types.
  1538. *
  1539. * @typedef {Object} ConstantsInterpolationSamplingType
  1540. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1541. * @property {string} LINEAR - Linear interpolation.
  1542. * @property {string} FLAT - Flat interpolation.
  1543. */
  1544. /**
  1545. * Represents the different interpolation sampling modes.
  1546. *
  1547. * @typedef {Object} ConstantsInterpolationSamplingMode
  1548. * @property {string} NORMAL - Normal sampling mode.
  1549. * @property {string} CENTROID - Centroid sampling mode.
  1550. * @property {string} SAMPLE - Sample-specific sampling mode.
  1551. * @property {string} FIRST - Flat interpolation using the first vertex.
  1552. * @property {string} EITHER - Flat interpolation using either vertex.
  1553. */
  1554. /**
  1555. * Finds the minimum value in an array.
  1556. *
  1557. * @private
  1558. * @param {Array<number>} array - The array to search for the minimum value.
  1559. * @return {number} The minimum value in the array, or Infinity if the array is empty.
  1560. */
  1561. /**
  1562. * Checks if an array contains values that require Uint32 representation.
  1563. *
  1564. * This function determines whether the array contains any values >= 65535,
  1565. * which would require a Uint32Array rather than a Uint16Array for proper storage.
  1566. * The function iterates from the end of the array, assuming larger values are
  1567. * typically located at the end.
  1568. *
  1569. * @private
  1570. * @param {Array<number>} array - The array to check.
  1571. * @return {boolean} True if the array contains values >= 65535, false otherwise.
  1572. */
  1573. function arrayNeedsUint32( array ) {
  1574. // assumes larger values usually on last
  1575. for ( let i = array.length - 1; i >= 0; -- i ) {
  1576. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1577. }
  1578. return false;
  1579. }
  1580. /**
  1581. * Map of typed array constructor names to their constructors.
  1582. * This mapping enables dynamic creation of typed arrays based on string type names.
  1583. *
  1584. * @private
  1585. * @constant
  1586. * @type {Object<string, TypedArrayConstructor>}
  1587. */
  1588. const TYPED_ARRAYS = {
  1589. Int8Array: Int8Array,
  1590. Uint8Array: Uint8Array,
  1591. Uint8ClampedArray: Uint8ClampedArray,
  1592. Int16Array: Int16Array,
  1593. Uint16Array: Uint16Array,
  1594. Int32Array: Int32Array,
  1595. Uint32Array: Uint32Array,
  1596. Float32Array: Float32Array,
  1597. Float64Array: Float64Array
  1598. };
  1599. /**
  1600. * Creates a typed array of the specified type from the given buffer.
  1601. *
  1602. * @private
  1603. * @param {string} type - The name of the typed array type (e.g., 'Float32Array', 'Uint16Array').
  1604. * @param {ArrayBuffer} buffer - The buffer to create the typed array from.
  1605. * @return {TypedArray} A new typed array of the specified type.
  1606. */
  1607. function getTypedArray( type, buffer ) {
  1608. return new TYPED_ARRAYS[ type ]( buffer );
  1609. }
  1610. /**
  1611. * Returns `true` if the given object is a typed array.
  1612. *
  1613. * @param {any} array - The object to check.
  1614. * @return {boolean} Whether the given object is a typed array.
  1615. */
  1616. function isTypedArray( array ) {
  1617. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1618. }
  1619. /**
  1620. * Creates an XHTML element with the specified tag name.
  1621. *
  1622. * This function uses the XHTML namespace to create DOM elements,
  1623. * ensuring proper element creation in XML-based contexts.
  1624. *
  1625. * @private
  1626. * @param {string} name - The tag name of the element to create (e.g., 'canvas', 'div').
  1627. * @return {HTMLElement} The created XHTML element.
  1628. */
  1629. function createElementNS( name ) {
  1630. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1631. }
  1632. /**
  1633. * Creates a canvas element configured for block display.
  1634. *
  1635. * This is a convenience function that creates a canvas element with
  1636. * display style set to 'block', which is commonly used in three.js
  1637. * rendering contexts to avoid inline element spacing issues.
  1638. *
  1639. * @return {HTMLCanvasElement} A canvas element with display set to 'block'.
  1640. */
  1641. function createCanvasElement() {
  1642. const canvas = createElementNS( 'canvas' );
  1643. canvas.style.display = 'block';
  1644. return canvas;
  1645. }
  1646. /**
  1647. * Internal cache for tracking warning messages to prevent duplicate warnings.
  1648. *
  1649. * @private
  1650. * @type {Object<string, boolean>}
  1651. */
  1652. const _cache = {};
  1653. /**
  1654. * Custom console function handler for intercepting log, warn, and error calls.
  1655. *
  1656. * @private
  1657. * @type {Function|null}
  1658. */
  1659. let _setConsoleFunction = null;
  1660. /**
  1661. * Sets a custom function to handle console output.
  1662. *
  1663. * This allows external code to intercept and handle console.log, console.warn,
  1664. * and console.error calls made by three.js, which is useful for custom logging,
  1665. * testing, or debugging workflows.
  1666. *
  1667. * @param {Function} fn - The function to handle console output. Should accept
  1668. * (type, message, ...params) where type is 'log', 'warn', or 'error'.
  1669. */
  1670. function setConsoleFunction( fn ) {
  1671. _setConsoleFunction = fn;
  1672. }
  1673. /**
  1674. * Gets the currently set custom console function.
  1675. *
  1676. * @return {Function|null} The custom console function, or null if not set.
  1677. */
  1678. function getConsoleFunction() {
  1679. return _setConsoleFunction;
  1680. }
  1681. /**
  1682. * Logs an informational message with the 'THREE.' prefix.
  1683. *
  1684. * If a custom console function is set via setConsoleFunction(), it will be used
  1685. * instead of the native console.log. The first parameter is treated as the
  1686. * method name and is automatically prefixed with 'THREE.'.
  1687. *
  1688. * @param {...any} params - The message components. The first param is used as
  1689. * the method name and prefixed with 'THREE.'.
  1690. */
  1691. function log( ...params ) {
  1692. const message = 'THREE.' + params.shift();
  1693. if ( _setConsoleFunction ) {
  1694. _setConsoleFunction( 'log', message, ...params );
  1695. } else {
  1696. console.log( message, ...params );
  1697. }
  1698. }
  1699. /**
  1700. * Logs a warning message with the 'THREE.' prefix.
  1701. *
  1702. * If a custom console function is set via setConsoleFunction(), it will be used
  1703. * instead of the native console.warn. The first parameter is treated as the
  1704. * method name and is automatically prefixed with 'THREE.'.
  1705. *
  1706. * @param {...any} params - The message components. The first param is used as
  1707. * the method name and prefixed with 'THREE.'.
  1708. */
  1709. function warn( ...params ) {
  1710. const message = 'THREE.' + params.shift();
  1711. if ( _setConsoleFunction ) {
  1712. _setConsoleFunction( 'warn', message, ...params );
  1713. } else {
  1714. console.warn( message, ...params );
  1715. }
  1716. }
  1717. /**
  1718. * Logs an error message with the 'THREE.' prefix.
  1719. *
  1720. * If a custom console function is set via setConsoleFunction(), it will be used
  1721. * instead of the native console.error. The first parameter is treated as the
  1722. * method name and is automatically prefixed with 'THREE.'.
  1723. *
  1724. * @param {...any} params - The message components. The first param is used as
  1725. * the method name and prefixed with 'THREE.'.
  1726. */
  1727. function error( ...params ) {
  1728. const message = 'THREE.' + params.shift();
  1729. if ( _setConsoleFunction ) {
  1730. _setConsoleFunction( 'error', message, ...params );
  1731. } else {
  1732. console.error( message, ...params );
  1733. }
  1734. }
  1735. /**
  1736. * Logs a warning message only once, preventing duplicate warnings.
  1737. *
  1738. * This function maintains an internal cache of warning messages and will only
  1739. * output each unique warning message once. Useful for warnings that may be
  1740. * triggered repeatedly but should only be shown to the user once.
  1741. *
  1742. * @param {...any} params - The warning message components.
  1743. */
  1744. function warnOnce( ...params ) {
  1745. const message = params.join( ' ' );
  1746. if ( message in _cache ) return;
  1747. _cache[ message ] = true;
  1748. warn( ...params );
  1749. }
  1750. /**
  1751. * Asynchronously probes for WebGL sync object completion.
  1752. *
  1753. * This function creates a promise that resolves when the WebGL sync object
  1754. * signals completion or rejects if the sync operation fails. It uses polling
  1755. * at the specified interval to check the sync status without blocking the
  1756. * main thread. This is useful for GPU-CPU synchronization in WebGL contexts.
  1757. *
  1758. * @private
  1759. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL rendering context.
  1760. * @param {WebGLSync} sync - The WebGL sync object to wait for.
  1761. * @param {number} interval - The polling interval in milliseconds.
  1762. * @return {Promise<void>} A promise that resolves when the sync completes or rejects if it fails.
  1763. */
  1764. function probeAsync( gl, sync, interval ) {
  1765. return new Promise( function ( resolve, reject ) {
  1766. function probe() {
  1767. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1768. case gl.WAIT_FAILED:
  1769. reject();
  1770. break;
  1771. case gl.TIMEOUT_EXPIRED:
  1772. setTimeout( probe, interval );
  1773. break;
  1774. default:
  1775. resolve();
  1776. }
  1777. }
  1778. setTimeout( probe, interval );
  1779. } );
  1780. }
  1781. /**
  1782. * This modules allows to dispatch event objects on custom JavaScript objects.
  1783. *
  1784. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1785. *
  1786. * Code Example:
  1787. * ```js
  1788. * class Car extends EventDispatcher {
  1789. * start() {
  1790. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1791. * }
  1792. *};
  1793. *
  1794. * // Using events with the custom object
  1795. * const car = new Car();
  1796. * car.addEventListener( 'start', function ( event ) {
  1797. * alert( event.message );
  1798. * } );
  1799. *
  1800. * car.start();
  1801. * ```
  1802. */
  1803. class EventDispatcher {
  1804. /**
  1805. * Adds the given event listener to the given event type.
  1806. *
  1807. * @param {string} type - The type of event to listen to.
  1808. * @param {Function} listener - The function that gets called when the event is fired.
  1809. */
  1810. addEventListener( type, listener ) {
  1811. if ( this._listeners === undefined ) this._listeners = {};
  1812. const listeners = this._listeners;
  1813. if ( listeners[ type ] === undefined ) {
  1814. listeners[ type ] = [];
  1815. }
  1816. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1817. listeners[ type ].push( listener );
  1818. }
  1819. }
  1820. /**
  1821. * Returns `true` if the given event listener has been added to the given event type.
  1822. *
  1823. * @param {string} type - The type of event.
  1824. * @param {Function} listener - The listener to check.
  1825. * @return {boolean} Whether the given event listener has been added to the given event type.
  1826. */
  1827. hasEventListener( type, listener ) {
  1828. const listeners = this._listeners;
  1829. if ( listeners === undefined ) return false;
  1830. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1831. }
  1832. /**
  1833. * Removes the given event listener from the given event type.
  1834. *
  1835. * @param {string} type - The type of event.
  1836. * @param {Function} listener - The listener to remove.
  1837. */
  1838. removeEventListener( type, listener ) {
  1839. const listeners = this._listeners;
  1840. if ( listeners === undefined ) return;
  1841. const listenerArray = listeners[ type ];
  1842. if ( listenerArray !== undefined ) {
  1843. const index = listenerArray.indexOf( listener );
  1844. if ( index !== -1 ) {
  1845. listenerArray.splice( index, 1 );
  1846. }
  1847. }
  1848. }
  1849. /**
  1850. * Dispatches an event object.
  1851. *
  1852. * @param {Object} event - The event that gets fired.
  1853. */
  1854. dispatchEvent( event ) {
  1855. const listeners = this._listeners;
  1856. if ( listeners === undefined ) return;
  1857. const listenerArray = listeners[ event.type ];
  1858. if ( listenerArray !== undefined ) {
  1859. event.target = this;
  1860. // Make a copy, in case listeners are removed while iterating.
  1861. const array = listenerArray.slice( 0 );
  1862. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1863. array[ i ].call( this, event );
  1864. }
  1865. event.target = null;
  1866. }
  1867. }
  1868. }
  1869. 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' ];
  1870. let _seed = 1234567;
  1871. const DEG2RAD = Math.PI / 180;
  1872. const RAD2DEG = 180 / Math.PI;
  1873. /**
  1874. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1875. * (universally unique identifier).
  1876. *
  1877. * @return {string} The UUID.
  1878. */
  1879. function generateUUID() {
  1880. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1881. const d0 = Math.random() * 0xffffffff | 0;
  1882. const d1 = Math.random() * 0xffffffff | 0;
  1883. const d2 = Math.random() * 0xffffffff | 0;
  1884. const d3 = Math.random() * 0xffffffff | 0;
  1885. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1886. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1887. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1888. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1889. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1890. return uuid.toLowerCase();
  1891. }
  1892. /**
  1893. * Clamps the given value between min and max.
  1894. *
  1895. * @param {number} value - The value to clamp.
  1896. * @param {number} min - The min value.
  1897. * @param {number} max - The max value.
  1898. * @return {number} The clamped value.
  1899. */
  1900. function clamp( value, min, max ) {
  1901. return Math.max( min, Math.min( max, value ) );
  1902. }
  1903. /**
  1904. * Computes the Euclidean modulo of the given parameters that
  1905. * is `( ( n % m ) + m ) % m`.
  1906. *
  1907. * @param {number} n - The first parameter.
  1908. * @param {number} m - The second parameter.
  1909. * @return {number} The Euclidean modulo.
  1910. */
  1911. function euclideanModulo( n, m ) {
  1912. // https://en.wikipedia.org/wiki/Modulo_operation
  1913. return ( ( n % m ) + m ) % m;
  1914. }
  1915. /**
  1916. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1917. * for the given value. `a2` must be greater than `a1`.
  1918. *
  1919. * @param {number} x - The value to be mapped.
  1920. * @param {number} a1 - Minimum value for range A.
  1921. * @param {number} a2 - Maximum value for range A.
  1922. * @param {number} b1 - Minimum value for range B.
  1923. * @param {number} b2 - Maximum value for range B.
  1924. * @return {number} The mapped value.
  1925. */
  1926. function mapLinear( x, a1, a2, b1, b2 ) {
  1927. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1928. }
  1929. /**
  1930. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1931. * between the start and end point.
  1932. *
  1933. * @param {number} x - The start point
  1934. * @param {number} y - The end point.
  1935. * @param {number} value - A value between start and end.
  1936. * @return {number} The interpolation factor.
  1937. */
  1938. function inverseLerp( x, y, value ) {
  1939. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1940. if ( x !== y ) {
  1941. return ( value - x ) / ( y - x );
  1942. } else {
  1943. return 0;
  1944. }
  1945. }
  1946. /**
  1947. * Returns a value linearly interpolated from two known points based on the given interval -
  1948. * `t = 0` will return `x` and `t = 1` will return `y`.
  1949. *
  1950. * @param {number} x - The start point
  1951. * @param {number} y - The end point.
  1952. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1953. * @return {number} The interpolated value.
  1954. */
  1955. function lerp( x, y, t ) {
  1956. return ( 1 - t ) * x + t * y;
  1957. }
  1958. /**
  1959. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1960. * time to maintain frame rate independent movement. For details, see
  1961. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  1962. *
  1963. * @param {number} x - The current point.
  1964. * @param {number} y - The target point.
  1965. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1966. * and a lower value will make the movement more gradual.
  1967. * @param {number} dt - Delta time in seconds.
  1968. * @return {number} The interpolated value.
  1969. */
  1970. function damp( x, y, lambda, dt ) {
  1971. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1972. }
  1973. /**
  1974. * Returns a value that alternates between `0` and the given `length` parameter.
  1975. *
  1976. * @param {number} x - The value to pingpong.
  1977. * @param {number} [length=1] - The positive value the function will pingpong to.
  1978. * @return {number} The alternated value.
  1979. */
  1980. function pingpong( x, length = 1 ) {
  1981. // https://www.desmos.com/calculator/vcsjnyz7x4
  1982. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1983. }
  1984. /**
  1985. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1986. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1987. * the `min` and `max`.
  1988. *
  1989. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  1990. *
  1991. * @param {number} x - The value to evaluate based on its position between `min` and `max`.
  1992. * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`.
  1993. * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`.
  1994. * @return {number} The alternated value.
  1995. */
  1996. function smoothstep( x, min, max ) {
  1997. if ( x <= min ) return 0;
  1998. if ( x >= max ) return 1;
  1999. x = ( x - min ) / ( max - min );
  2000. return x * x * ( 3 - 2 * x );
  2001. }
  2002. /**
  2003. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2004. * that has zero 1st and 2nd order derivatives at `x=0` and `x=1`.
  2005. *
  2006. * @param {number} x - The value to evaluate based on its position between `min` and `max`.
  2007. * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`.
  2008. * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`.
  2009. * @return {number} The alternated value.
  2010. */
  2011. function smootherstep( x, min, max ) {
  2012. if ( x <= min ) return 0;
  2013. if ( x >= max ) return 1;
  2014. x = ( x - min ) / ( max - min );
  2015. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  2016. }
  2017. /**
  2018. * Returns a random integer from `<low, high>` interval.
  2019. *
  2020. * @param {number} low - The lower value boundary.
  2021. * @param {number} high - The upper value boundary
  2022. * @return {number} A random integer.
  2023. */
  2024. function randInt( low, high ) {
  2025. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2026. }
  2027. /**
  2028. * Returns a random float from `<low, high>` interval.
  2029. *
  2030. * @param {number} low - The lower value boundary.
  2031. * @param {number} high - The upper value boundary
  2032. * @return {number} A random float.
  2033. */
  2034. function randFloat( low, high ) {
  2035. return low + Math.random() * ( high - low );
  2036. }
  2037. /**
  2038. * Returns a random integer from `<-range/2, range/2>` interval.
  2039. *
  2040. * @param {number} range - Defines the value range.
  2041. * @return {number} A random float.
  2042. */
  2043. function randFloatSpread( range ) {
  2044. return range * ( 0.5 - Math.random() );
  2045. }
  2046. /**
  2047. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2048. *
  2049. * @param {number} [s] - The integer seed.
  2050. * @return {number} A random float.
  2051. */
  2052. function seededRandom( s ) {
  2053. if ( s !== undefined ) _seed = s;
  2054. // Mulberry32 generator
  2055. let t = _seed += 0x6D2B79F5;
  2056. t = Math.imul( t ^ t >>> 15, t | 1 );
  2057. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  2058. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  2059. }
  2060. /**
  2061. * Converts degrees to radians.
  2062. *
  2063. * @param {number} degrees - A value in degrees.
  2064. * @return {number} The converted value in radians.
  2065. */
  2066. function degToRad( degrees ) {
  2067. return degrees * DEG2RAD;
  2068. }
  2069. /**
  2070. * Converts radians to degrees.
  2071. *
  2072. * @param {number} radians - A value in radians.
  2073. * @return {number} The converted value in degrees.
  2074. */
  2075. function radToDeg( radians ) {
  2076. return radians * RAD2DEG;
  2077. }
  2078. /**
  2079. * Returns `true` if the given number is a power of two.
  2080. *
  2081. * @param {number} value - The value to check.
  2082. * @return {boolean} Whether the given number is a power of two or not.
  2083. */
  2084. function isPowerOfTwo( value ) {
  2085. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  2086. }
  2087. /**
  2088. * Returns the smallest power of two that is greater than or equal to the given number.
  2089. *
  2090. * @param {number} value - The value to find a POT for. Must be greater than `0`.
  2091. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2092. */
  2093. function ceilPowerOfTwo( value ) {
  2094. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  2095. }
  2096. /**
  2097. * Returns the largest power of two that is less than or equal to the given number.
  2098. *
  2099. * @param {number} value - The value to find a POT for. Must be greater than `0`.
  2100. * @return {number} The largest power of two that is less than or equal to the given number.
  2101. */
  2102. function floorPowerOfTwo( value ) {
  2103. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  2104. }
  2105. /**
  2106. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2107. * defined by the given angles and order.
  2108. *
  2109. * Rotations are applied to the axes in the order specified by order:
  2110. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2111. *
  2112. * @param {Quaternion} q - The quaternion to set.
  2113. * @param {number} a - The rotation applied to the first axis, in radians.
  2114. * @param {number} b - The rotation applied to the second axis, in radians.
  2115. * @param {number} c - The rotation applied to the third axis, in radians.
  2116. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2117. */
  2118. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  2119. const cos = Math.cos;
  2120. const sin = Math.sin;
  2121. const c2 = cos( b / 2 );
  2122. const s2 = sin( b / 2 );
  2123. const c13 = cos( ( a + c ) / 2 );
  2124. const s13 = sin( ( a + c ) / 2 );
  2125. const c1_3 = cos( ( a - c ) / 2 );
  2126. const s1_3 = sin( ( a - c ) / 2 );
  2127. const c3_1 = cos( ( c - a ) / 2 );
  2128. const s3_1 = sin( ( c - a ) / 2 );
  2129. switch ( order ) {
  2130. case 'XYX':
  2131. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  2132. break;
  2133. case 'YZY':
  2134. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  2135. break;
  2136. case 'ZXZ':
  2137. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  2138. break;
  2139. case 'XZX':
  2140. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  2141. break;
  2142. case 'YXY':
  2143. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  2144. break;
  2145. case 'ZYZ':
  2146. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  2147. break;
  2148. default:
  2149. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  2150. }
  2151. }
  2152. /**
  2153. * Denormalizes the given value according to the given typed array.
  2154. *
  2155. * @param {number} value - The value to denormalize.
  2156. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2157. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2158. */
  2159. function denormalize( value, array ) {
  2160. switch ( array.constructor ) {
  2161. case Float32Array:
  2162. return value;
  2163. case Uint32Array:
  2164. return value / 4294967295.0;
  2165. case Uint16Array:
  2166. return value / 65535.0;
  2167. case Uint8Array:
  2168. return value / 255.0;
  2169. case Int32Array:
  2170. return Math.max( value / 2147483647.0, -1 );
  2171. case Int16Array:
  2172. return Math.max( value / 32767.0, -1 );
  2173. case Int8Array:
  2174. return Math.max( value / 127.0, -1 );
  2175. default:
  2176. throw new Error( 'Invalid component type.' );
  2177. }
  2178. }
  2179. /**
  2180. * Normalizes the given value according to the given typed array.
  2181. *
  2182. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2183. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2184. * @return {number} The normalize value.
  2185. */
  2186. function normalize( value, array ) {
  2187. switch ( array.constructor ) {
  2188. case Float32Array:
  2189. return value;
  2190. case Uint32Array:
  2191. return Math.round( value * 4294967295.0 );
  2192. case Uint16Array:
  2193. return Math.round( value * 65535.0 );
  2194. case Uint8Array:
  2195. return Math.round( value * 255.0 );
  2196. case Int32Array:
  2197. return Math.round( value * 2147483647.0 );
  2198. case Int16Array:
  2199. return Math.round( value * 32767.0 );
  2200. case Int8Array:
  2201. return Math.round( value * 127.0 );
  2202. default:
  2203. throw new Error( 'Invalid component type.' );
  2204. }
  2205. }
  2206. /**
  2207. * @class
  2208. * @classdesc A collection of math utility functions.
  2209. * @hideconstructor
  2210. */
  2211. const MathUtils = {
  2212. DEG2RAD: DEG2RAD,
  2213. RAD2DEG: RAD2DEG,
  2214. /**
  2215. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2216. * (universally unique identifier).
  2217. *
  2218. * @static
  2219. * @method
  2220. * @return {string} The UUID.
  2221. */
  2222. generateUUID: generateUUID,
  2223. /**
  2224. * Clamps the given value between min and max.
  2225. *
  2226. * @static
  2227. * @method
  2228. * @param {number} value - The value to clamp.
  2229. * @param {number} min - The min value.
  2230. * @param {number} max - The max value.
  2231. * @return {number} The clamped value.
  2232. */
  2233. clamp: clamp,
  2234. /**
  2235. * Computes the Euclidean modulo of the given parameters that
  2236. * is `( ( n % m ) + m ) % m`.
  2237. *
  2238. * @static
  2239. * @method
  2240. * @param {number} n - The first parameter.
  2241. * @param {number} m - The second parameter.
  2242. * @return {number} The Euclidean modulo.
  2243. */
  2244. euclideanModulo: euclideanModulo,
  2245. /**
  2246. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2247. * for the given value.
  2248. *
  2249. * @static
  2250. * @method
  2251. * @param {number} x - The value to be mapped.
  2252. * @param {number} a1 - Minimum value for range A.
  2253. * @param {number} a2 - Maximum value for range A.
  2254. * @param {number} b1 - Minimum value for range B.
  2255. * @param {number} b2 - Maximum value for range B.
  2256. * @return {number} The mapped value.
  2257. */
  2258. mapLinear: mapLinear,
  2259. /**
  2260. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2261. * between the start and end point.
  2262. *
  2263. * @static
  2264. * @method
  2265. * @param {number} x - The start point
  2266. * @param {number} y - The end point.
  2267. * @param {number} value - A value between start and end.
  2268. * @return {number} The interpolation factor.
  2269. */
  2270. inverseLerp: inverseLerp,
  2271. /**
  2272. * Returns a value linearly interpolated from two known points based on the given interval -
  2273. * `t = 0` will return `x` and `t = 1` will return `y`.
  2274. *
  2275. * @static
  2276. * @method
  2277. * @param {number} x - The start point
  2278. * @param {number} y - The end point.
  2279. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2280. * @return {number} The interpolated value.
  2281. */
  2282. lerp: lerp,
  2283. /**
  2284. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2285. * time to maintain frame rate independent movement. For details, see
  2286. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2287. *
  2288. * @static
  2289. * @method
  2290. * @param {number} x - The current point.
  2291. * @param {number} y - The target point.
  2292. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2293. * and a lower value will make the movement more gradual.
  2294. * @param {number} dt - Delta time in seconds.
  2295. * @return {number} The interpolated value.
  2296. */
  2297. damp: damp,
  2298. /**
  2299. * Returns a value that alternates between `0` and the given `length` parameter.
  2300. *
  2301. * @static
  2302. * @method
  2303. * @param {number} x - The value to pingpong.
  2304. * @param {number} [length=1] - The positive value the function will pingpong to.
  2305. * @return {number} The alternated value.
  2306. */
  2307. pingpong: pingpong,
  2308. /**
  2309. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2310. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2311. * the `min` and `max`.
  2312. *
  2313. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2314. *
  2315. * @static
  2316. * @method
  2317. * @param {number} x - The value to evaluate based on its position between min and max.
  2318. * @param {number} min - The min value. Any x value below min will be `0`.
  2319. * @param {number} max - The max value. Any x value above max will be `1`.
  2320. * @return {number} The alternated value.
  2321. */
  2322. smoothstep: smoothstep,
  2323. /**
  2324. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2325. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2326. *
  2327. * @static
  2328. * @method
  2329. * @param {number} x - The value to evaluate based on its position between min and max.
  2330. * @param {number} min - The min value. Any x value below min will be `0`.
  2331. * @param {number} max - The max value. Any x value above max will be `1`.
  2332. * @return {number} The alternated value.
  2333. */
  2334. smootherstep: smootherstep,
  2335. /**
  2336. * Returns a random integer from `<low, high>` interval.
  2337. *
  2338. * @static
  2339. * @method
  2340. * @param {number} low - The lower value boundary.
  2341. * @param {number} high - The upper value boundary
  2342. * @return {number} A random integer.
  2343. */
  2344. randInt: randInt,
  2345. /**
  2346. * Returns a random float from `<low, high>` interval.
  2347. *
  2348. * @static
  2349. * @method
  2350. * @param {number} low - The lower value boundary.
  2351. * @param {number} high - The upper value boundary
  2352. * @return {number} A random float.
  2353. */
  2354. randFloat: randFloat,
  2355. /**
  2356. * Returns a random integer from `<-range/2, range/2>` interval.
  2357. *
  2358. * @static
  2359. * @method
  2360. * @param {number} range - Defines the value range.
  2361. * @return {number} A random float.
  2362. */
  2363. randFloatSpread: randFloatSpread,
  2364. /**
  2365. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2366. *
  2367. * @static
  2368. * @method
  2369. * @param {number} [s] - The integer seed.
  2370. * @return {number} A random float.
  2371. */
  2372. seededRandom: seededRandom,
  2373. /**
  2374. * Converts degrees to radians.
  2375. *
  2376. * @static
  2377. * @method
  2378. * @param {number} degrees - A value in degrees.
  2379. * @return {number} The converted value in radians.
  2380. */
  2381. degToRad: degToRad,
  2382. /**
  2383. * Converts radians to degrees.
  2384. *
  2385. * @static
  2386. * @method
  2387. * @param {number} radians - A value in radians.
  2388. * @return {number} The converted value in degrees.
  2389. */
  2390. radToDeg: radToDeg,
  2391. /**
  2392. * Returns `true` if the given number is a power of two.
  2393. *
  2394. * @static
  2395. * @method
  2396. * @param {number} value - The value to check.
  2397. * @return {boolean} Whether the given number is a power of two or not.
  2398. */
  2399. isPowerOfTwo: isPowerOfTwo,
  2400. /**
  2401. * Returns the smallest power of two that is greater than or equal to the given number.
  2402. *
  2403. * @static
  2404. * @method
  2405. * @param {number} value - The value to find a POT for.
  2406. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2407. */
  2408. ceilPowerOfTwo: ceilPowerOfTwo,
  2409. /**
  2410. * Returns the largest power of two that is less than or equal to the given number.
  2411. *
  2412. * @static
  2413. * @method
  2414. * @param {number} value - The value to find a POT for.
  2415. * @return {number} The largest power of two that is less than or equal to the given number.
  2416. */
  2417. floorPowerOfTwo: floorPowerOfTwo,
  2418. /**
  2419. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2420. * defined by the given angles and order.
  2421. *
  2422. * Rotations are applied to the axes in the order specified by order:
  2423. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2424. *
  2425. * @static
  2426. * @method
  2427. * @param {Quaternion} q - The quaternion to set.
  2428. * @param {number} a - The rotation applied to the first axis, in radians.
  2429. * @param {number} b - The rotation applied to the second axis, in radians.
  2430. * @param {number} c - The rotation applied to the third axis, in radians.
  2431. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2432. */
  2433. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2434. /**
  2435. * Normalizes the given value according to the given typed array.
  2436. *
  2437. * @static
  2438. * @method
  2439. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2440. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2441. * @return {number} The normalize value.
  2442. */
  2443. normalize: normalize,
  2444. /**
  2445. * Denormalizes the given value according to the given typed array.
  2446. *
  2447. * @static
  2448. * @method
  2449. * @param {number} value - The value to denormalize.
  2450. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2451. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2452. */
  2453. denormalize: denormalize
  2454. };
  2455. /**
  2456. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2457. * (labeled x and y), which can be used to represent a number of things, such as:
  2458. *
  2459. * - A point in 2D space (i.e. a position on a plane).
  2460. * - A direction and length across a plane. In three.js the length will
  2461. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2462. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2463. * - Any arbitrary ordered pair of numbers.
  2464. *
  2465. * There are other things a 2D vector can be used to represent, such as
  2466. * momentum vectors, complex numbers and so on, however these are the most
  2467. * common uses in three.js.
  2468. *
  2469. * Iterating through a vector instance will yield its components `(x, y)` in
  2470. * the corresponding order.
  2471. * ```js
  2472. * const a = new THREE.Vector2( 0, 1 );
  2473. *
  2474. * //no arguments; will be initialised to (0, 0)
  2475. * const b = new THREE.Vector2( );
  2476. *
  2477. * const d = a.distanceTo( b );
  2478. * ```
  2479. */
  2480. class Vector2 {
  2481. /**
  2482. * Constructs a new 2D vector.
  2483. *
  2484. * @param {number} [x=0] - The x value of this vector.
  2485. * @param {number} [y=0] - The y value of this vector.
  2486. */
  2487. constructor( x = 0, y = 0 ) {
  2488. /**
  2489. * This flag can be used for type testing.
  2490. *
  2491. * @type {boolean}
  2492. * @readonly
  2493. * @default true
  2494. */
  2495. Vector2.prototype.isVector2 = true;
  2496. /**
  2497. * The x value of this vector.
  2498. *
  2499. * @type {number}
  2500. */
  2501. this.x = x;
  2502. /**
  2503. * The y value of this vector.
  2504. *
  2505. * @type {number}
  2506. */
  2507. this.y = y;
  2508. }
  2509. /**
  2510. * Alias for {@link Vector2#x}.
  2511. *
  2512. * @type {number}
  2513. */
  2514. get width() {
  2515. return this.x;
  2516. }
  2517. set width( value ) {
  2518. this.x = value;
  2519. }
  2520. /**
  2521. * Alias for {@link Vector2#y}.
  2522. *
  2523. * @type {number}
  2524. */
  2525. get height() {
  2526. return this.y;
  2527. }
  2528. set height( value ) {
  2529. this.y = value;
  2530. }
  2531. /**
  2532. * Sets the vector components.
  2533. *
  2534. * @param {number} x - The value of the x component.
  2535. * @param {number} y - The value of the y component.
  2536. * @return {Vector2} A reference to this vector.
  2537. */
  2538. set( x, y ) {
  2539. this.x = x;
  2540. this.y = y;
  2541. return this;
  2542. }
  2543. /**
  2544. * Sets the vector components to the same value.
  2545. *
  2546. * @param {number} scalar - The value to set for all vector components.
  2547. * @return {Vector2} A reference to this vector.
  2548. */
  2549. setScalar( scalar ) {
  2550. this.x = scalar;
  2551. this.y = scalar;
  2552. return this;
  2553. }
  2554. /**
  2555. * Sets the vector's x component to the given value
  2556. *
  2557. * @param {number} x - The value to set.
  2558. * @return {Vector2} A reference to this vector.
  2559. */
  2560. setX( x ) {
  2561. this.x = x;
  2562. return this;
  2563. }
  2564. /**
  2565. * Sets the vector's y component to the given value
  2566. *
  2567. * @param {number} y - The value to set.
  2568. * @return {Vector2} A reference to this vector.
  2569. */
  2570. setY( y ) {
  2571. this.y = y;
  2572. return this;
  2573. }
  2574. /**
  2575. * Allows to set a vector component with an index.
  2576. *
  2577. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2578. * @param {number} value - The value to set.
  2579. * @return {Vector2} A reference to this vector.
  2580. */
  2581. setComponent( index, value ) {
  2582. switch ( index ) {
  2583. case 0: this.x = value; break;
  2584. case 1: this.y = value; break;
  2585. default: throw new Error( 'index is out of range: ' + index );
  2586. }
  2587. return this;
  2588. }
  2589. /**
  2590. * Returns the value of the vector component which matches the given index.
  2591. *
  2592. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2593. * @return {number} A vector component value.
  2594. */
  2595. getComponent( index ) {
  2596. switch ( index ) {
  2597. case 0: return this.x;
  2598. case 1: return this.y;
  2599. default: throw new Error( 'index is out of range: ' + index );
  2600. }
  2601. }
  2602. /**
  2603. * Returns a new vector with copied values from this instance.
  2604. *
  2605. * @return {Vector2} A clone of this instance.
  2606. */
  2607. clone() {
  2608. return new this.constructor( this.x, this.y );
  2609. }
  2610. /**
  2611. * Copies the values of the given vector to this instance.
  2612. *
  2613. * @param {Vector2} v - The vector to copy.
  2614. * @return {Vector2} A reference to this vector.
  2615. */
  2616. copy( v ) {
  2617. this.x = v.x;
  2618. this.y = v.y;
  2619. return this;
  2620. }
  2621. /**
  2622. * Adds the given vector to this instance.
  2623. *
  2624. * @param {Vector2} v - The vector to add.
  2625. * @return {Vector2} A reference to this vector.
  2626. */
  2627. add( v ) {
  2628. this.x += v.x;
  2629. this.y += v.y;
  2630. return this;
  2631. }
  2632. /**
  2633. * Adds the given scalar value to all components of this instance.
  2634. *
  2635. * @param {number} s - The scalar to add.
  2636. * @return {Vector2} A reference to this vector.
  2637. */
  2638. addScalar( s ) {
  2639. this.x += s;
  2640. this.y += s;
  2641. return this;
  2642. }
  2643. /**
  2644. * Adds the given vectors and stores the result in this instance.
  2645. *
  2646. * @param {Vector2} a - The first vector.
  2647. * @param {Vector2} b - The second vector.
  2648. * @return {Vector2} A reference to this vector.
  2649. */
  2650. addVectors( a, b ) {
  2651. this.x = a.x + b.x;
  2652. this.y = a.y + b.y;
  2653. return this;
  2654. }
  2655. /**
  2656. * Adds the given vector scaled by the given factor to this instance.
  2657. *
  2658. * @param {Vector2} v - The vector.
  2659. * @param {number} s - The factor that scales `v`.
  2660. * @return {Vector2} A reference to this vector.
  2661. */
  2662. addScaledVector( v, s ) {
  2663. this.x += v.x * s;
  2664. this.y += v.y * s;
  2665. return this;
  2666. }
  2667. /**
  2668. * Subtracts the given vector from this instance.
  2669. *
  2670. * @param {Vector2} v - The vector to subtract.
  2671. * @return {Vector2} A reference to this vector.
  2672. */
  2673. sub( v ) {
  2674. this.x -= v.x;
  2675. this.y -= v.y;
  2676. return this;
  2677. }
  2678. /**
  2679. * Subtracts the given scalar value from all components of this instance.
  2680. *
  2681. * @param {number} s - The scalar to subtract.
  2682. * @return {Vector2} A reference to this vector.
  2683. */
  2684. subScalar( s ) {
  2685. this.x -= s;
  2686. this.y -= s;
  2687. return this;
  2688. }
  2689. /**
  2690. * Subtracts the given vectors and stores the result in this instance.
  2691. *
  2692. * @param {Vector2} a - The first vector.
  2693. * @param {Vector2} b - The second vector.
  2694. * @return {Vector2} A reference to this vector.
  2695. */
  2696. subVectors( a, b ) {
  2697. this.x = a.x - b.x;
  2698. this.y = a.y - b.y;
  2699. return this;
  2700. }
  2701. /**
  2702. * Multiplies the given vector with this instance.
  2703. *
  2704. * @param {Vector2} v - The vector to multiply.
  2705. * @return {Vector2} A reference to this vector.
  2706. */
  2707. multiply( v ) {
  2708. this.x *= v.x;
  2709. this.y *= v.y;
  2710. return this;
  2711. }
  2712. /**
  2713. * Multiplies the given scalar value with all components of this instance.
  2714. *
  2715. * @param {number} scalar - The scalar to multiply.
  2716. * @return {Vector2} A reference to this vector.
  2717. */
  2718. multiplyScalar( scalar ) {
  2719. this.x *= scalar;
  2720. this.y *= scalar;
  2721. return this;
  2722. }
  2723. /**
  2724. * Divides this instance by the given vector.
  2725. *
  2726. * @param {Vector2} v - The vector to divide.
  2727. * @return {Vector2} A reference to this vector.
  2728. */
  2729. divide( v ) {
  2730. this.x /= v.x;
  2731. this.y /= v.y;
  2732. return this;
  2733. }
  2734. /**
  2735. * Divides this vector by the given scalar.
  2736. *
  2737. * @param {number} scalar - The scalar to divide.
  2738. * @return {Vector2} A reference to this vector.
  2739. */
  2740. divideScalar( scalar ) {
  2741. return this.multiplyScalar( 1 / scalar );
  2742. }
  2743. /**
  2744. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2745. * the given 3x3 matrix.
  2746. *
  2747. * @param {Matrix3} m - The matrix to apply.
  2748. * @return {Vector2} A reference to this vector.
  2749. */
  2750. applyMatrix3( m ) {
  2751. const x = this.x, y = this.y;
  2752. const e = m.elements;
  2753. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2754. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2755. return this;
  2756. }
  2757. /**
  2758. * If this vector's x or y value is greater than the given vector's x or y
  2759. * value, replace that value with the corresponding min value.
  2760. *
  2761. * @param {Vector2} v - The vector.
  2762. * @return {Vector2} A reference to this vector.
  2763. */
  2764. min( v ) {
  2765. this.x = Math.min( this.x, v.x );
  2766. this.y = Math.min( this.y, v.y );
  2767. return this;
  2768. }
  2769. /**
  2770. * If this vector's x or y value is less than the given vector's x or y
  2771. * value, replace that value with the corresponding max value.
  2772. *
  2773. * @param {Vector2} v - The vector.
  2774. * @return {Vector2} A reference to this vector.
  2775. */
  2776. max( v ) {
  2777. this.x = Math.max( this.x, v.x );
  2778. this.y = Math.max( this.y, v.y );
  2779. return this;
  2780. }
  2781. /**
  2782. * If this vector's x or y value is greater than the max vector's x or y
  2783. * value, it is replaced by the corresponding value.
  2784. * If this vector's x or y value is less than the min vector's x or y value,
  2785. * it is replaced by the corresponding value.
  2786. *
  2787. * @param {Vector2} min - The minimum x and y values.
  2788. * @param {Vector2} max - The maximum x and y values in the desired range.
  2789. * @return {Vector2} A reference to this vector.
  2790. */
  2791. clamp( min, max ) {
  2792. // assumes min < max, componentwise
  2793. this.x = clamp( this.x, min.x, max.x );
  2794. this.y = clamp( this.y, min.y, max.y );
  2795. return this;
  2796. }
  2797. /**
  2798. * If this vector's x or y values are greater than the max value, they are
  2799. * replaced by the max value.
  2800. * If this vector's x or y values are less than the min value, they are
  2801. * replaced by the min value.
  2802. *
  2803. * @param {number} minVal - The minimum value the components will be clamped to.
  2804. * @param {number} maxVal - The maximum value the components will be clamped to.
  2805. * @return {Vector2} A reference to this vector.
  2806. */
  2807. clampScalar( minVal, maxVal ) {
  2808. this.x = clamp( this.x, minVal, maxVal );
  2809. this.y = clamp( this.y, minVal, maxVal );
  2810. return this;
  2811. }
  2812. /**
  2813. * If this vector's length is greater than the max value, it is replaced by
  2814. * the max value.
  2815. * If this vector's length is less than the min value, it is replaced by the
  2816. * min value.
  2817. *
  2818. * @param {number} min - The minimum value the vector length will be clamped to.
  2819. * @param {number} max - The maximum value the vector length will be clamped to.
  2820. * @return {Vector2} A reference to this vector.
  2821. */
  2822. clampLength( min, max ) {
  2823. const length = this.length();
  2824. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2825. }
  2826. /**
  2827. * The components of this vector are rounded down to the nearest integer value.
  2828. *
  2829. * @return {Vector2} A reference to this vector.
  2830. */
  2831. floor() {
  2832. this.x = Math.floor( this.x );
  2833. this.y = Math.floor( this.y );
  2834. return this;
  2835. }
  2836. /**
  2837. * The components of this vector are rounded up to the nearest integer value.
  2838. *
  2839. * @return {Vector2} A reference to this vector.
  2840. */
  2841. ceil() {
  2842. this.x = Math.ceil( this.x );
  2843. this.y = Math.ceil( this.y );
  2844. return this;
  2845. }
  2846. /**
  2847. * The components of this vector are rounded to the nearest integer value
  2848. *
  2849. * @return {Vector2} A reference to this vector.
  2850. */
  2851. round() {
  2852. this.x = Math.round( this.x );
  2853. this.y = Math.round( this.y );
  2854. return this;
  2855. }
  2856. /**
  2857. * The components of this vector are rounded towards zero (up if negative,
  2858. * down if positive) to an integer value.
  2859. *
  2860. * @return {Vector2} A reference to this vector.
  2861. */
  2862. roundToZero() {
  2863. this.x = Math.trunc( this.x );
  2864. this.y = Math.trunc( this.y );
  2865. return this;
  2866. }
  2867. /**
  2868. * Inverts this vector - i.e. sets x = -x and y = -y.
  2869. *
  2870. * @return {Vector2} A reference to this vector.
  2871. */
  2872. negate() {
  2873. this.x = - this.x;
  2874. this.y = - this.y;
  2875. return this;
  2876. }
  2877. /**
  2878. * Calculates the dot product of the given vector with this instance.
  2879. *
  2880. * @param {Vector2} v - The vector to compute the dot product with.
  2881. * @return {number} The result of the dot product.
  2882. */
  2883. dot( v ) {
  2884. return this.x * v.x + this.y * v.y;
  2885. }
  2886. /**
  2887. * Calculates the cross product of the given vector with this instance.
  2888. *
  2889. * @param {Vector2} v - The vector to compute the cross product with.
  2890. * @return {number} The result of the cross product.
  2891. */
  2892. cross( v ) {
  2893. return this.x * v.y - this.y * v.x;
  2894. }
  2895. /**
  2896. * Computes the square of the Euclidean length (straight-line length) from
  2897. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2898. * compare the length squared instead as it is slightly more efficient to calculate.
  2899. *
  2900. * @return {number} The square length of this vector.
  2901. */
  2902. lengthSq() {
  2903. return this.x * this.x + this.y * this.y;
  2904. }
  2905. /**
  2906. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2907. *
  2908. * @return {number} The length of this vector.
  2909. */
  2910. length() {
  2911. return Math.sqrt( this.x * this.x + this.y * this.y );
  2912. }
  2913. /**
  2914. * Computes the Manhattan length of this vector.
  2915. *
  2916. * @return {number} The length of this vector.
  2917. */
  2918. manhattanLength() {
  2919. return Math.abs( this.x ) + Math.abs( this.y );
  2920. }
  2921. /**
  2922. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2923. * with the same direction as this one, but with a vector length of `1`.
  2924. *
  2925. * @return {Vector2} A reference to this vector.
  2926. */
  2927. normalize() {
  2928. return this.divideScalar( this.length() || 1 );
  2929. }
  2930. /**
  2931. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2932. *
  2933. * @return {number} The angle in radians.
  2934. */
  2935. angle() {
  2936. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2937. return angle;
  2938. }
  2939. /**
  2940. * Returns the angle between the given vector and this instance in radians.
  2941. *
  2942. * @param {Vector2} v - The vector to compute the angle with.
  2943. * @return {number} The angle in radians.
  2944. */
  2945. angleTo( v ) {
  2946. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2947. if ( denominator === 0 ) return Math.PI / 2;
  2948. const theta = this.dot( v ) / denominator;
  2949. // clamp, to handle numerical problems
  2950. return Math.acos( clamp( theta, -1, 1 ) );
  2951. }
  2952. /**
  2953. * Computes the distance from the given vector to this instance.
  2954. *
  2955. * @param {Vector2} v - The vector to compute the distance to.
  2956. * @return {number} The distance.
  2957. */
  2958. distanceTo( v ) {
  2959. return Math.sqrt( this.distanceToSquared( v ) );
  2960. }
  2961. /**
  2962. * Computes the squared distance from the given vector to this instance.
  2963. * If you are just comparing the distance with another distance, you should compare
  2964. * the distance squared instead as it is slightly more efficient to calculate.
  2965. *
  2966. * @param {Vector2} v - The vector to compute the squared distance to.
  2967. * @return {number} The squared distance.
  2968. */
  2969. distanceToSquared( v ) {
  2970. const dx = this.x - v.x, dy = this.y - v.y;
  2971. return dx * dx + dy * dy;
  2972. }
  2973. /**
  2974. * Computes the Manhattan distance from the given vector to this instance.
  2975. *
  2976. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2977. * @return {number} The Manhattan distance.
  2978. */
  2979. manhattanDistanceTo( v ) {
  2980. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2981. }
  2982. /**
  2983. * Sets this vector to a vector with the same direction as this one, but
  2984. * with the specified length.
  2985. *
  2986. * @param {number} length - The new length of this vector.
  2987. * @return {Vector2} A reference to this vector.
  2988. */
  2989. setLength( length ) {
  2990. return this.normalize().multiplyScalar( length );
  2991. }
  2992. /**
  2993. * Linearly interpolates between the given vector and this instance, where
  2994. * alpha is the percent distance along the line - alpha = 0 will be this
  2995. * vector, and alpha = 1 will be the given one.
  2996. *
  2997. * @param {Vector2} v - The vector to interpolate towards.
  2998. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2999. * @return {Vector2} A reference to this vector.
  3000. */
  3001. lerp( v, alpha ) {
  3002. this.x += ( v.x - this.x ) * alpha;
  3003. this.y += ( v.y - this.y ) * alpha;
  3004. return this;
  3005. }
  3006. /**
  3007. * Linearly interpolates between the given vectors, where alpha is the percent
  3008. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  3009. * be the second one. The result is stored in this instance.
  3010. *
  3011. * @param {Vector2} v1 - The first vector.
  3012. * @param {Vector2} v2 - The second vector.
  3013. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3014. * @return {Vector2} A reference to this vector.
  3015. */
  3016. lerpVectors( v1, v2, alpha ) {
  3017. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3018. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3019. return this;
  3020. }
  3021. /**
  3022. * Returns `true` if this vector is equal with the given one.
  3023. *
  3024. * @param {Vector2} v - The vector to test for equality.
  3025. * @return {boolean} Whether this vector is equal with the given one.
  3026. */
  3027. equals( v ) {
  3028. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  3029. }
  3030. /**
  3031. * Sets this vector's x value to be `array[ offset ]` and y
  3032. * value to be `array[ offset + 1 ]`.
  3033. *
  3034. * @param {Array<number>} array - An array holding the vector component values.
  3035. * @param {number} [offset=0] - The offset into the array.
  3036. * @return {Vector2} A reference to this vector.
  3037. */
  3038. fromArray( array, offset = 0 ) {
  3039. this.x = array[ offset ];
  3040. this.y = array[ offset + 1 ];
  3041. return this;
  3042. }
  3043. /**
  3044. * Writes the components of this vector to the given array. If no array is provided,
  3045. * the method returns a new instance.
  3046. *
  3047. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  3048. * @param {number} [offset=0] - Index of the first element in the array.
  3049. * @return {Array<number>} The vector components.
  3050. */
  3051. toArray( array = [], offset = 0 ) {
  3052. array[ offset ] = this.x;
  3053. array[ offset + 1 ] = this.y;
  3054. return array;
  3055. }
  3056. /**
  3057. * Sets the components of this vector from the given buffer attribute.
  3058. *
  3059. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  3060. * @param {number} index - The index into the attribute.
  3061. * @return {Vector2} A reference to this vector.
  3062. */
  3063. fromBufferAttribute( attribute, index ) {
  3064. this.x = attribute.getX( index );
  3065. this.y = attribute.getY( index );
  3066. return this;
  3067. }
  3068. /**
  3069. * Rotates this vector around the given center by the given angle.
  3070. *
  3071. * @param {Vector2} center - The point around which to rotate.
  3072. * @param {number} angle - The angle to rotate, in radians.
  3073. * @return {Vector2} A reference to this vector.
  3074. */
  3075. rotateAround( center, angle ) {
  3076. const c = Math.cos( angle ), s = Math.sin( angle );
  3077. const x = this.x - center.x;
  3078. const y = this.y - center.y;
  3079. this.x = x * c - y * s + center.x;
  3080. this.y = x * s + y * c + center.y;
  3081. return this;
  3082. }
  3083. /**
  3084. * Sets each component of this vector to a pseudo-random value between `0` and
  3085. * `1`, excluding `1`.
  3086. *
  3087. * @return {Vector2} A reference to this vector.
  3088. */
  3089. random() {
  3090. this.x = Math.random();
  3091. this.y = Math.random();
  3092. return this;
  3093. }
  3094. *[ Symbol.iterator ]() {
  3095. yield this.x;
  3096. yield this.y;
  3097. }
  3098. }
  3099. /**
  3100. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  3101. *
  3102. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  3103. * the corresponding order.
  3104. *
  3105. * Note that three.js expects Quaternions to be normalized.
  3106. * ```js
  3107. * const quaternion = new THREE.Quaternion();
  3108. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  3109. *
  3110. * const vector = new THREE.Vector3( 1, 0, 0 );
  3111. * vector.applyQuaternion( quaternion );
  3112. * ```
  3113. */
  3114. class Quaternion {
  3115. /**
  3116. * Constructs a new quaternion.
  3117. *
  3118. * @param {number} [x=0] - The x value of this quaternion.
  3119. * @param {number} [y=0] - The y value of this quaternion.
  3120. * @param {number} [z=0] - The z value of this quaternion.
  3121. * @param {number} [w=1] - The w value of this quaternion.
  3122. */
  3123. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  3124. /**
  3125. * This flag can be used for type testing.
  3126. *
  3127. * @type {boolean}
  3128. * @readonly
  3129. * @default true
  3130. */
  3131. this.isQuaternion = true;
  3132. this._x = x;
  3133. this._y = y;
  3134. this._z = z;
  3135. this._w = w;
  3136. }
  3137. /**
  3138. * Interpolates between two quaternions via SLERP. This implementation assumes the
  3139. * quaternion data are managed in flat arrays.
  3140. *
  3141. * @param {Array<number>} dst - The destination array.
  3142. * @param {number} dstOffset - An offset into the destination array.
  3143. * @param {Array<number>} src0 - The source array of the first quaternion.
  3144. * @param {number} srcOffset0 - An offset into the first source array.
  3145. * @param {Array<number>} src1 - The source array of the second quaternion.
  3146. * @param {number} srcOffset1 - An offset into the second source array.
  3147. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3148. * @see {@link Quaternion#slerp}
  3149. */
  3150. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3151. let x0 = src0[ srcOffset0 + 0 ],
  3152. y0 = src0[ srcOffset0 + 1 ],
  3153. z0 = src0[ srcOffset0 + 2 ],
  3154. w0 = src0[ srcOffset0 + 3 ];
  3155. let x1 = src1[ srcOffset1 + 0 ],
  3156. y1 = src1[ srcOffset1 + 1 ],
  3157. z1 = src1[ srcOffset1 + 2 ],
  3158. w1 = src1[ srcOffset1 + 3 ];
  3159. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3160. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3161. if ( dot < 0 ) {
  3162. x1 = - x1;
  3163. y1 = - y1;
  3164. z1 = - z1;
  3165. w1 = - w1;
  3166. dot = - dot;
  3167. }
  3168. let s = 1 - t;
  3169. if ( dot < 0.9995 ) {
  3170. // slerp
  3171. const theta = Math.acos( dot );
  3172. const sin = Math.sin( theta );
  3173. s = Math.sin( s * theta ) / sin;
  3174. t = Math.sin( t * theta ) / sin;
  3175. x0 = x0 * s + x1 * t;
  3176. y0 = y0 * s + y1 * t;
  3177. z0 = z0 * s + z1 * t;
  3178. w0 = w0 * s + w1 * t;
  3179. } else {
  3180. // for small angles, lerp then normalize
  3181. x0 = x0 * s + x1 * t;
  3182. y0 = y0 * s + y1 * t;
  3183. z0 = z0 * s + z1 * t;
  3184. w0 = w0 * s + w1 * t;
  3185. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3186. x0 *= f;
  3187. y0 *= f;
  3188. z0 *= f;
  3189. w0 *= f;
  3190. }
  3191. }
  3192. dst[ dstOffset ] = x0;
  3193. dst[ dstOffset + 1 ] = y0;
  3194. dst[ dstOffset + 2 ] = z0;
  3195. dst[ dstOffset + 3 ] = w0;
  3196. }
  3197. /**
  3198. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3199. * in flat arrays.
  3200. *
  3201. * @param {Array<number>} dst - The destination array.
  3202. * @param {number} dstOffset - An offset into the destination array.
  3203. * @param {Array<number>} src0 - The source array of the first quaternion.
  3204. * @param {number} srcOffset0 - An offset into the first source array.
  3205. * @param {Array<number>} src1 - The source array of the second quaternion.
  3206. * @param {number} srcOffset1 - An offset into the second source array.
  3207. * @return {Array<number>} The destination array.
  3208. * @see {@link Quaternion#multiplyQuaternions}.
  3209. */
  3210. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3211. const x0 = src0[ srcOffset0 ];
  3212. const y0 = src0[ srcOffset0 + 1 ];
  3213. const z0 = src0[ srcOffset0 + 2 ];
  3214. const w0 = src0[ srcOffset0 + 3 ];
  3215. const x1 = src1[ srcOffset1 ];
  3216. const y1 = src1[ srcOffset1 + 1 ];
  3217. const z1 = src1[ srcOffset1 + 2 ];
  3218. const w1 = src1[ srcOffset1 + 3 ];
  3219. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3220. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3221. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3222. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3223. return dst;
  3224. }
  3225. /**
  3226. * The x value of this quaternion.
  3227. *
  3228. * @type {number}
  3229. * @default 0
  3230. */
  3231. get x() {
  3232. return this._x;
  3233. }
  3234. set x( value ) {
  3235. this._x = value;
  3236. this._onChangeCallback();
  3237. }
  3238. /**
  3239. * The y value of this quaternion.
  3240. *
  3241. * @type {number}
  3242. * @default 0
  3243. */
  3244. get y() {
  3245. return this._y;
  3246. }
  3247. set y( value ) {
  3248. this._y = value;
  3249. this._onChangeCallback();
  3250. }
  3251. /**
  3252. * The z value of this quaternion.
  3253. *
  3254. * @type {number}
  3255. * @default 0
  3256. */
  3257. get z() {
  3258. return this._z;
  3259. }
  3260. set z( value ) {
  3261. this._z = value;
  3262. this._onChangeCallback();
  3263. }
  3264. /**
  3265. * The w value of this quaternion.
  3266. *
  3267. * @type {number}
  3268. * @default 1
  3269. */
  3270. get w() {
  3271. return this._w;
  3272. }
  3273. set w( value ) {
  3274. this._w = value;
  3275. this._onChangeCallback();
  3276. }
  3277. /**
  3278. * Sets the quaternion components.
  3279. *
  3280. * @param {number} x - The x value of this quaternion.
  3281. * @param {number} y - The y value of this quaternion.
  3282. * @param {number} z - The z value of this quaternion.
  3283. * @param {number} w - The w value of this quaternion.
  3284. * @return {Quaternion} A reference to this quaternion.
  3285. */
  3286. set( x, y, z, w ) {
  3287. this._x = x;
  3288. this._y = y;
  3289. this._z = z;
  3290. this._w = w;
  3291. this._onChangeCallback();
  3292. return this;
  3293. }
  3294. /**
  3295. * Returns a new quaternion with copied values from this instance.
  3296. *
  3297. * @return {Quaternion} A clone of this instance.
  3298. */
  3299. clone() {
  3300. return new this.constructor( this._x, this._y, this._z, this._w );
  3301. }
  3302. /**
  3303. * Copies the values of the given quaternion to this instance.
  3304. *
  3305. * @param {Quaternion} quaternion - The quaternion to copy.
  3306. * @return {Quaternion} A reference to this quaternion.
  3307. */
  3308. copy( quaternion ) {
  3309. this._x = quaternion.x;
  3310. this._y = quaternion.y;
  3311. this._z = quaternion.z;
  3312. this._w = quaternion.w;
  3313. this._onChangeCallback();
  3314. return this;
  3315. }
  3316. /**
  3317. * Sets this quaternion from the rotation specified by the given
  3318. * Euler angles.
  3319. *
  3320. * @param {Euler} euler - The Euler angles.
  3321. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3322. * @return {Quaternion} A reference to this quaternion.
  3323. */
  3324. setFromEuler( euler, update = true ) {
  3325. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3326. // http://www.mathworks.com/matlabcentral/fileexchange/
  3327. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3328. // content/SpinCalc.m
  3329. const cos = Math.cos;
  3330. const sin = Math.sin;
  3331. const c1 = cos( x / 2 );
  3332. const c2 = cos( y / 2 );
  3333. const c3 = cos( z / 2 );
  3334. const s1 = sin( x / 2 );
  3335. const s2 = sin( y / 2 );
  3336. const s3 = sin( z / 2 );
  3337. switch ( order ) {
  3338. case 'XYZ':
  3339. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3340. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3341. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3342. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3343. break;
  3344. case 'YXZ':
  3345. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3346. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3347. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3348. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3349. break;
  3350. case 'ZXY':
  3351. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3352. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3353. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3354. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3355. break;
  3356. case 'ZYX':
  3357. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3358. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3359. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3360. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3361. break;
  3362. case 'YZX':
  3363. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3364. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3365. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3366. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3367. break;
  3368. case 'XZY':
  3369. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3370. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3371. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3372. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3373. break;
  3374. default:
  3375. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3376. }
  3377. if ( update === true ) this._onChangeCallback();
  3378. return this;
  3379. }
  3380. /**
  3381. * Sets this quaternion from the given axis and angle.
  3382. *
  3383. * @param {Vector3} axis - The normalized axis.
  3384. * @param {number} angle - The angle in radians.
  3385. * @return {Quaternion} A reference to this quaternion.
  3386. */
  3387. setFromAxisAngle( axis, angle ) {
  3388. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3389. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3390. this._x = axis.x * s;
  3391. this._y = axis.y * s;
  3392. this._z = axis.z * s;
  3393. this._w = Math.cos( halfAngle );
  3394. this._onChangeCallback();
  3395. return this;
  3396. }
  3397. /**
  3398. * Sets this quaternion from the given rotation matrix.
  3399. *
  3400. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3401. * @return {Quaternion} A reference to this quaternion.
  3402. */
  3403. setFromRotationMatrix( m ) {
  3404. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3405. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3406. const te = m.elements,
  3407. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3408. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3409. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3410. trace = m11 + m22 + m33;
  3411. if ( trace > 0 ) {
  3412. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3413. this._w = 0.25 / s;
  3414. this._x = ( m32 - m23 ) * s;
  3415. this._y = ( m13 - m31 ) * s;
  3416. this._z = ( m21 - m12 ) * s;
  3417. } else if ( m11 > m22 && m11 > m33 ) {
  3418. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3419. this._w = ( m32 - m23 ) / s;
  3420. this._x = 0.25 * s;
  3421. this._y = ( m12 + m21 ) / s;
  3422. this._z = ( m13 + m31 ) / s;
  3423. } else if ( m22 > m33 ) {
  3424. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3425. this._w = ( m13 - m31 ) / s;
  3426. this._x = ( m12 + m21 ) / s;
  3427. this._y = 0.25 * s;
  3428. this._z = ( m23 + m32 ) / s;
  3429. } else {
  3430. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3431. this._w = ( m21 - m12 ) / s;
  3432. this._x = ( m13 + m31 ) / s;
  3433. this._y = ( m23 + m32 ) / s;
  3434. this._z = 0.25 * s;
  3435. }
  3436. this._onChangeCallback();
  3437. return this;
  3438. }
  3439. /**
  3440. * Sets this quaternion to the rotation required to rotate the direction vector
  3441. * `vFrom` to the direction vector `vTo`.
  3442. *
  3443. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3444. * @param {Vector3} vTo - The second (normalized) direction vector.
  3445. * @return {Quaternion} A reference to this quaternion.
  3446. */
  3447. setFromUnitVectors( vFrom, vTo ) {
  3448. // assumes direction vectors vFrom and vTo are normalized
  3449. let r = vFrom.dot( vTo ) + 1;
  3450. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3451. // vFrom and vTo point in opposite directions
  3452. r = 0;
  3453. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3454. this._x = - vFrom.y;
  3455. this._y = vFrom.x;
  3456. this._z = 0;
  3457. this._w = r;
  3458. } else {
  3459. this._x = 0;
  3460. this._y = - vFrom.z;
  3461. this._z = vFrom.y;
  3462. this._w = r;
  3463. }
  3464. } else {
  3465. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3466. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3467. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3468. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3469. this._w = r;
  3470. }
  3471. return this.normalize();
  3472. }
  3473. /**
  3474. * Returns the angle between this quaternion and the given one in radians.
  3475. *
  3476. * @param {Quaternion} q - The quaternion to compute the angle with.
  3477. * @return {number} The angle in radians.
  3478. */
  3479. angleTo( q ) {
  3480. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3481. }
  3482. /**
  3483. * Rotates this quaternion by a given angular step to the given quaternion.
  3484. * The method ensures that the final quaternion will not overshoot `q`.
  3485. *
  3486. * @param {Quaternion} q - The target quaternion.
  3487. * @param {number} step - The angular step in radians.
  3488. * @return {Quaternion} A reference to this quaternion.
  3489. */
  3490. rotateTowards( q, step ) {
  3491. const angle = this.angleTo( q );
  3492. if ( angle === 0 ) return this;
  3493. const t = Math.min( 1, step / angle );
  3494. this.slerp( q, t );
  3495. return this;
  3496. }
  3497. /**
  3498. * Sets this quaternion to the identity quaternion; that is, to the
  3499. * quaternion that represents "no rotation".
  3500. *
  3501. * @return {Quaternion} A reference to this quaternion.
  3502. */
  3503. identity() {
  3504. return this.set( 0, 0, 0, 1 );
  3505. }
  3506. /**
  3507. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3508. * quaternion is assumed to have unit length.
  3509. *
  3510. * @return {Quaternion} A reference to this quaternion.
  3511. */
  3512. invert() {
  3513. return this.conjugate();
  3514. }
  3515. /**
  3516. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3517. * quaternion represents the same rotation in the opposite direction about
  3518. * the rotational axis.
  3519. *
  3520. * @return {Quaternion} A reference to this quaternion.
  3521. */
  3522. conjugate() {
  3523. this._x *= -1;
  3524. this._y *= -1;
  3525. this._z *= -1;
  3526. this._onChangeCallback();
  3527. return this;
  3528. }
  3529. /**
  3530. * Calculates the dot product of this quaternion and the given one.
  3531. *
  3532. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3533. * @return {number} The result of the dot product.
  3534. */
  3535. dot( v ) {
  3536. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3537. }
  3538. /**
  3539. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3540. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3541. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3542. * {@link Quaternion#length}.
  3543. *
  3544. * @return {number} The squared Euclidean length.
  3545. */
  3546. lengthSq() {
  3547. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3548. }
  3549. /**
  3550. * Computes the Euclidean length (straight-line length) of this quaternion,
  3551. * considered as a 4 dimensional vector.
  3552. *
  3553. * @return {number} The Euclidean length.
  3554. */
  3555. length() {
  3556. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3557. }
  3558. /**
  3559. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3560. * the same rotation as this one, but has a length equal to `1`.
  3561. *
  3562. * @return {Quaternion} A reference to this quaternion.
  3563. */
  3564. normalize() {
  3565. let l = this.length();
  3566. if ( l === 0 ) {
  3567. this._x = 0;
  3568. this._y = 0;
  3569. this._z = 0;
  3570. this._w = 1;
  3571. } else {
  3572. l = 1 / l;
  3573. this._x = this._x * l;
  3574. this._y = this._y * l;
  3575. this._z = this._z * l;
  3576. this._w = this._w * l;
  3577. }
  3578. this._onChangeCallback();
  3579. return this;
  3580. }
  3581. /**
  3582. * Multiplies this quaternion by the given one.
  3583. *
  3584. * @param {Quaternion} q - The quaternion.
  3585. * @return {Quaternion} A reference to this quaternion.
  3586. */
  3587. multiply( q ) {
  3588. return this.multiplyQuaternions( this, q );
  3589. }
  3590. /**
  3591. * Pre-multiplies this quaternion by the given one.
  3592. *
  3593. * @param {Quaternion} q - The quaternion.
  3594. * @return {Quaternion} A reference to this quaternion.
  3595. */
  3596. premultiply( q ) {
  3597. return this.multiplyQuaternions( q, this );
  3598. }
  3599. /**
  3600. * Multiplies the given quaternions and stores the result in this instance.
  3601. *
  3602. * @param {Quaternion} a - The first quaternion.
  3603. * @param {Quaternion} b - The second quaternion.
  3604. * @return {Quaternion} A reference to this quaternion.
  3605. */
  3606. multiplyQuaternions( a, b ) {
  3607. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3608. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3609. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3610. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3611. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3612. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3613. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3614. this._onChangeCallback();
  3615. return this;
  3616. }
  3617. /**
  3618. * Performs a spherical linear interpolation between this quaternion and the target quaternion.
  3619. *
  3620. * @param {Quaternion} qb - The target quaternion.
  3621. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3622. * @return {Quaternion} A reference to this quaternion.
  3623. */
  3624. slerp( qb, t ) {
  3625. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3626. let dot = this.dot( qb );
  3627. if ( dot < 0 ) {
  3628. x = - x;
  3629. y = - y;
  3630. z = - z;
  3631. w = - w;
  3632. dot = - dot;
  3633. }
  3634. let s = 1 - t;
  3635. if ( dot < 0.9995 ) {
  3636. // slerp
  3637. const theta = Math.acos( dot );
  3638. const sin = Math.sin( theta );
  3639. s = Math.sin( s * theta ) / sin;
  3640. t = Math.sin( t * theta ) / sin;
  3641. this._x = this._x * s + x * t;
  3642. this._y = this._y * s + y * t;
  3643. this._z = this._z * s + z * t;
  3644. this._w = this._w * s + w * t;
  3645. this._onChangeCallback();
  3646. } else {
  3647. // for small angles, lerp then normalize
  3648. this._x = this._x * s + x * t;
  3649. this._y = this._y * s + y * t;
  3650. this._z = this._z * s + z * t;
  3651. this._w = this._w * s + w * t;
  3652. this.normalize(); // normalize calls _onChangeCallback()
  3653. }
  3654. return this;
  3655. }
  3656. /**
  3657. * Performs a spherical linear interpolation between the given quaternions
  3658. * and stores the result in this quaternion.
  3659. *
  3660. * @param {Quaternion} qa - The source quaternion.
  3661. * @param {Quaternion} qb - The target quaternion.
  3662. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3663. * @return {Quaternion} A reference to this quaternion.
  3664. */
  3665. slerpQuaternions( qa, qb, t ) {
  3666. return this.copy( qa ).slerp( qb, t );
  3667. }
  3668. /**
  3669. * Sets this quaternion to a uniformly random, normalized quaternion.
  3670. *
  3671. * @return {Quaternion} A reference to this quaternion.
  3672. */
  3673. random() {
  3674. // Ken Shoemake
  3675. // Uniform random rotations
  3676. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3677. const theta1 = 2 * Math.PI * Math.random();
  3678. const theta2 = 2 * Math.PI * Math.random();
  3679. const x0 = Math.random();
  3680. const r1 = Math.sqrt( 1 - x0 );
  3681. const r2 = Math.sqrt( x0 );
  3682. return this.set(
  3683. r1 * Math.sin( theta1 ),
  3684. r1 * Math.cos( theta1 ),
  3685. r2 * Math.sin( theta2 ),
  3686. r2 * Math.cos( theta2 ),
  3687. );
  3688. }
  3689. /**
  3690. * Returns `true` if this quaternion is equal with the given one.
  3691. *
  3692. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3693. * @return {boolean} Whether this quaternion is equal with the given one.
  3694. */
  3695. equals( quaternion ) {
  3696. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3697. }
  3698. /**
  3699. * Sets this quaternion's components from the given array.
  3700. *
  3701. * @param {Array<number>} array - An array holding the quaternion component values.
  3702. * @param {number} [offset=0] - The offset into the array.
  3703. * @return {Quaternion} A reference to this quaternion.
  3704. */
  3705. fromArray( array, offset = 0 ) {
  3706. this._x = array[ offset ];
  3707. this._y = array[ offset + 1 ];
  3708. this._z = array[ offset + 2 ];
  3709. this._w = array[ offset + 3 ];
  3710. this._onChangeCallback();
  3711. return this;
  3712. }
  3713. /**
  3714. * Writes the components of this quaternion to the given array. If no array is provided,
  3715. * the method returns a new instance.
  3716. *
  3717. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3718. * @param {number} [offset=0] - Index of the first element in the array.
  3719. * @return {Array<number>} The quaternion components.
  3720. */
  3721. toArray( array = [], offset = 0 ) {
  3722. array[ offset ] = this._x;
  3723. array[ offset + 1 ] = this._y;
  3724. array[ offset + 2 ] = this._z;
  3725. array[ offset + 3 ] = this._w;
  3726. return array;
  3727. }
  3728. /**
  3729. * Sets the components of this quaternion from the given buffer attribute.
  3730. *
  3731. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3732. * @param {number} index - The index into the attribute.
  3733. * @return {Quaternion} A reference to this quaternion.
  3734. */
  3735. fromBufferAttribute( attribute, index ) {
  3736. this._x = attribute.getX( index );
  3737. this._y = attribute.getY( index );
  3738. this._z = attribute.getZ( index );
  3739. this._w = attribute.getW( index );
  3740. this._onChangeCallback();
  3741. return this;
  3742. }
  3743. /**
  3744. * This methods defines the serialization result of this class. Returns the
  3745. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3746. *
  3747. * @return {Array<number>} The serialized quaternion.
  3748. */
  3749. toJSON() {
  3750. return this.toArray();
  3751. }
  3752. _onChange( callback ) {
  3753. this._onChangeCallback = callback;
  3754. return this;
  3755. }
  3756. _onChangeCallback() {}
  3757. *[ Symbol.iterator ]() {
  3758. yield this._x;
  3759. yield this._y;
  3760. yield this._z;
  3761. yield this._w;
  3762. }
  3763. }
  3764. /**
  3765. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3766. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3767. *
  3768. * - A point in 3D space.
  3769. * - A direction and length in 3D space. In three.js the length will
  3770. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3771. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3772. * - Any arbitrary ordered triplet of numbers.
  3773. *
  3774. * There are other things a 3D vector can be used to represent, such as
  3775. * momentum vectors and so on, however these are the most
  3776. * common uses in three.js.
  3777. *
  3778. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3779. * the corresponding order.
  3780. * ```js
  3781. * const a = new THREE.Vector3( 0, 1, 0 );
  3782. *
  3783. * //no arguments; will be initialised to (0, 0, 0)
  3784. * const b = new THREE.Vector3( );
  3785. *
  3786. * const d = a.distanceTo( b );
  3787. * ```
  3788. */
  3789. class Vector3 {
  3790. /**
  3791. * Constructs a new 3D vector.
  3792. *
  3793. * @param {number} [x=0] - The x value of this vector.
  3794. * @param {number} [y=0] - The y value of this vector.
  3795. * @param {number} [z=0] - The z value of this vector.
  3796. */
  3797. constructor( x = 0, y = 0, z = 0 ) {
  3798. /**
  3799. * This flag can be used for type testing.
  3800. *
  3801. * @type {boolean}
  3802. * @readonly
  3803. * @default true
  3804. */
  3805. Vector3.prototype.isVector3 = true;
  3806. /**
  3807. * The x value of this vector.
  3808. *
  3809. * @type {number}
  3810. */
  3811. this.x = x;
  3812. /**
  3813. * The y value of this vector.
  3814. *
  3815. * @type {number}
  3816. */
  3817. this.y = y;
  3818. /**
  3819. * The z value of this vector.
  3820. *
  3821. * @type {number}
  3822. */
  3823. this.z = z;
  3824. }
  3825. /**
  3826. * Sets the vector components.
  3827. *
  3828. * @param {number} x - The value of the x component.
  3829. * @param {number} y - The value of the y component.
  3830. * @param {number} z - The value of the z component.
  3831. * @return {Vector3} A reference to this vector.
  3832. */
  3833. set( x, y, z ) {
  3834. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3835. this.x = x;
  3836. this.y = y;
  3837. this.z = z;
  3838. return this;
  3839. }
  3840. /**
  3841. * Sets the vector components to the same value.
  3842. *
  3843. * @param {number} scalar - The value to set for all vector components.
  3844. * @return {Vector3} A reference to this vector.
  3845. */
  3846. setScalar( scalar ) {
  3847. this.x = scalar;
  3848. this.y = scalar;
  3849. this.z = scalar;
  3850. return this;
  3851. }
  3852. /**
  3853. * Sets the vector's x component to the given value.
  3854. *
  3855. * @param {number} x - The value to set.
  3856. * @return {Vector3} A reference to this vector.
  3857. */
  3858. setX( x ) {
  3859. this.x = x;
  3860. return this;
  3861. }
  3862. /**
  3863. * Sets the vector's y component to the given value.
  3864. *
  3865. * @param {number} y - The value to set.
  3866. * @return {Vector3} A reference to this vector.
  3867. */
  3868. setY( y ) {
  3869. this.y = y;
  3870. return this;
  3871. }
  3872. /**
  3873. * Sets the vector's z component to the given value.
  3874. *
  3875. * @param {number} z - The value to set.
  3876. * @return {Vector3} A reference to this vector.
  3877. */
  3878. setZ( z ) {
  3879. this.z = z;
  3880. return this;
  3881. }
  3882. /**
  3883. * Allows to set a vector component with an index.
  3884. *
  3885. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3886. * @param {number} value - The value to set.
  3887. * @return {Vector3} A reference to this vector.
  3888. */
  3889. setComponent( index, value ) {
  3890. switch ( index ) {
  3891. case 0: this.x = value; break;
  3892. case 1: this.y = value; break;
  3893. case 2: this.z = value; break;
  3894. default: throw new Error( 'index is out of range: ' + index );
  3895. }
  3896. return this;
  3897. }
  3898. /**
  3899. * Returns the value of the vector component which matches the given index.
  3900. *
  3901. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3902. * @return {number} A vector component value.
  3903. */
  3904. getComponent( index ) {
  3905. switch ( index ) {
  3906. case 0: return this.x;
  3907. case 1: return this.y;
  3908. case 2: return this.z;
  3909. default: throw new Error( 'index is out of range: ' + index );
  3910. }
  3911. }
  3912. /**
  3913. * Returns a new vector with copied values from this instance.
  3914. *
  3915. * @return {Vector3} A clone of this instance.
  3916. */
  3917. clone() {
  3918. return new this.constructor( this.x, this.y, this.z );
  3919. }
  3920. /**
  3921. * Copies the values of the given vector to this instance.
  3922. *
  3923. * @param {Vector3} v - The vector to copy.
  3924. * @return {Vector3} A reference to this vector.
  3925. */
  3926. copy( v ) {
  3927. this.x = v.x;
  3928. this.y = v.y;
  3929. this.z = v.z;
  3930. return this;
  3931. }
  3932. /**
  3933. * Adds the given vector to this instance.
  3934. *
  3935. * @param {Vector3} v - The vector to add.
  3936. * @return {Vector3} A reference to this vector.
  3937. */
  3938. add( v ) {
  3939. this.x += v.x;
  3940. this.y += v.y;
  3941. this.z += v.z;
  3942. return this;
  3943. }
  3944. /**
  3945. * Adds the given scalar value to all components of this instance.
  3946. *
  3947. * @param {number} s - The scalar to add.
  3948. * @return {Vector3} A reference to this vector.
  3949. */
  3950. addScalar( s ) {
  3951. this.x += s;
  3952. this.y += s;
  3953. this.z += s;
  3954. return this;
  3955. }
  3956. /**
  3957. * Adds the given vectors and stores the result in this instance.
  3958. *
  3959. * @param {Vector3} a - The first vector.
  3960. * @param {Vector3} b - The second vector.
  3961. * @return {Vector3} A reference to this vector.
  3962. */
  3963. addVectors( a, b ) {
  3964. this.x = a.x + b.x;
  3965. this.y = a.y + b.y;
  3966. this.z = a.z + b.z;
  3967. return this;
  3968. }
  3969. /**
  3970. * Adds the given vector scaled by the given factor to this instance.
  3971. *
  3972. * @param {Vector3|Vector4} v - The vector.
  3973. * @param {number} s - The factor that scales `v`.
  3974. * @return {Vector3} A reference to this vector.
  3975. */
  3976. addScaledVector( v, s ) {
  3977. this.x += v.x * s;
  3978. this.y += v.y * s;
  3979. this.z += v.z * s;
  3980. return this;
  3981. }
  3982. /**
  3983. * Subtracts the given vector from this instance.
  3984. *
  3985. * @param {Vector3} v - The vector to subtract.
  3986. * @return {Vector3} A reference to this vector.
  3987. */
  3988. sub( v ) {
  3989. this.x -= v.x;
  3990. this.y -= v.y;
  3991. this.z -= v.z;
  3992. return this;
  3993. }
  3994. /**
  3995. * Subtracts the given scalar value from all components of this instance.
  3996. *
  3997. * @param {number} s - The scalar to subtract.
  3998. * @return {Vector3} A reference to this vector.
  3999. */
  4000. subScalar( s ) {
  4001. this.x -= s;
  4002. this.y -= s;
  4003. this.z -= s;
  4004. return this;
  4005. }
  4006. /**
  4007. * Subtracts the given vectors and stores the result in this instance.
  4008. *
  4009. * @param {Vector3} a - The first vector.
  4010. * @param {Vector3} b - The second vector.
  4011. * @return {Vector3} A reference to this vector.
  4012. */
  4013. subVectors( a, b ) {
  4014. this.x = a.x - b.x;
  4015. this.y = a.y - b.y;
  4016. this.z = a.z - b.z;
  4017. return this;
  4018. }
  4019. /**
  4020. * Multiplies the given vector with this instance.
  4021. *
  4022. * @param {Vector3} v - The vector to multiply.
  4023. * @return {Vector3} A reference to this vector.
  4024. */
  4025. multiply( v ) {
  4026. this.x *= v.x;
  4027. this.y *= v.y;
  4028. this.z *= v.z;
  4029. return this;
  4030. }
  4031. /**
  4032. * Multiplies the given scalar value with all components of this instance.
  4033. *
  4034. * @param {number} scalar - The scalar to multiply.
  4035. * @return {Vector3} A reference to this vector.
  4036. */
  4037. multiplyScalar( scalar ) {
  4038. this.x *= scalar;
  4039. this.y *= scalar;
  4040. this.z *= scalar;
  4041. return this;
  4042. }
  4043. /**
  4044. * Multiplies the given vectors and stores the result in this instance.
  4045. *
  4046. * @param {Vector3} a - The first vector.
  4047. * @param {Vector3} b - The second vector.
  4048. * @return {Vector3} A reference to this vector.
  4049. */
  4050. multiplyVectors( a, b ) {
  4051. this.x = a.x * b.x;
  4052. this.y = a.y * b.y;
  4053. this.z = a.z * b.z;
  4054. return this;
  4055. }
  4056. /**
  4057. * Applies the given Euler rotation to this vector.
  4058. *
  4059. * @param {Euler} euler - The Euler angles.
  4060. * @return {Vector3} A reference to this vector.
  4061. */
  4062. applyEuler( euler ) {
  4063. return this.applyQuaternion( _quaternion$5.setFromEuler( euler ) );
  4064. }
  4065. /**
  4066. * Applies a rotation specified by an axis and an angle to this vector.
  4067. *
  4068. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  4069. * @param {number} angle - The angle in radians.
  4070. * @return {Vector3} A reference to this vector.
  4071. */
  4072. applyAxisAngle( axis, angle ) {
  4073. return this.applyQuaternion( _quaternion$5.setFromAxisAngle( axis, angle ) );
  4074. }
  4075. /**
  4076. * Multiplies this vector with the given 3x3 matrix.
  4077. *
  4078. * @param {Matrix3} m - The 3x3 matrix.
  4079. * @return {Vector3} A reference to this vector.
  4080. */
  4081. applyMatrix3( m ) {
  4082. const x = this.x, y = this.y, z = this.z;
  4083. const e = m.elements;
  4084. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  4085. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  4086. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  4087. return this;
  4088. }
  4089. /**
  4090. * Multiplies this vector by the given normal matrix and normalizes
  4091. * the result.
  4092. *
  4093. * @param {Matrix3} m - The normal matrix.
  4094. * @return {Vector3} A reference to this vector.
  4095. */
  4096. applyNormalMatrix( m ) {
  4097. return this.applyMatrix3( m ).normalize();
  4098. }
  4099. /**
  4100. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  4101. * divides by perspective.
  4102. *
  4103. * @param {Matrix4} m - The matrix to apply.
  4104. * @return {Vector3} A reference to this vector.
  4105. */
  4106. applyMatrix4( m ) {
  4107. const x = this.x, y = this.y, z = this.z;
  4108. const e = m.elements;
  4109. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  4110. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  4111. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  4112. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  4113. return this;
  4114. }
  4115. /**
  4116. * Applies the given Quaternion to this vector.
  4117. *
  4118. * @param {Quaternion} q - The Quaternion.
  4119. * @return {Vector3} A reference to this vector.
  4120. */
  4121. applyQuaternion( q ) {
  4122. // quaternion q is assumed to have unit length
  4123. const vx = this.x, vy = this.y, vz = this.z;
  4124. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  4125. // t = 2 * cross( q.xyz, v );
  4126. const tx = 2 * ( qy * vz - qz * vy );
  4127. const ty = 2 * ( qz * vx - qx * vz );
  4128. const tz = 2 * ( qx * vy - qy * vx );
  4129. // v + q.w * t + cross( q.xyz, t );
  4130. this.x = vx + qw * tx + qy * tz - qz * ty;
  4131. this.y = vy + qw * ty + qz * tx - qx * tz;
  4132. this.z = vz + qw * tz + qx * ty - qy * tx;
  4133. return this;
  4134. }
  4135. /**
  4136. * Projects this vector from world space into the camera's normalized
  4137. * device coordinate (NDC) space.
  4138. *
  4139. * @param {Camera} camera - The camera.
  4140. * @return {Vector3} A reference to this vector.
  4141. */
  4142. project( camera ) {
  4143. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4144. }
  4145. /**
  4146. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4147. * space into world space.
  4148. *
  4149. * @param {Camera} camera - The camera.
  4150. * @return {Vector3} A reference to this vector.
  4151. */
  4152. unproject( camera ) {
  4153. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4154. }
  4155. /**
  4156. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4157. * subset of the given 4x4 matrix and then normalizes the result.
  4158. *
  4159. * @param {Matrix4} m - The matrix.
  4160. * @return {Vector3} A reference to this vector.
  4161. */
  4162. transformDirection( m ) {
  4163. // input: THREE.Matrix4 affine matrix
  4164. // vector interpreted as a direction
  4165. const x = this.x, y = this.y, z = this.z;
  4166. const e = m.elements;
  4167. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4168. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4169. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4170. return this.normalize();
  4171. }
  4172. /**
  4173. * Divides this instance by the given vector.
  4174. *
  4175. * @param {Vector3} v - The vector to divide.
  4176. * @return {Vector3} A reference to this vector.
  4177. */
  4178. divide( v ) {
  4179. this.x /= v.x;
  4180. this.y /= v.y;
  4181. this.z /= v.z;
  4182. return this;
  4183. }
  4184. /**
  4185. * Divides this vector by the given scalar.
  4186. *
  4187. * @param {number} scalar - The scalar to divide.
  4188. * @return {Vector3} A reference to this vector.
  4189. */
  4190. divideScalar( scalar ) {
  4191. return this.multiplyScalar( 1 / scalar );
  4192. }
  4193. /**
  4194. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4195. * value, replace that value with the corresponding min value.
  4196. *
  4197. * @param {Vector3} v - The vector.
  4198. * @return {Vector3} A reference to this vector.
  4199. */
  4200. min( v ) {
  4201. this.x = Math.min( this.x, v.x );
  4202. this.y = Math.min( this.y, v.y );
  4203. this.z = Math.min( this.z, v.z );
  4204. return this;
  4205. }
  4206. /**
  4207. * If this vector's x, y or z value is less than the given vector's x, y or z
  4208. * value, replace that value with the corresponding max value.
  4209. *
  4210. * @param {Vector3} v - The vector.
  4211. * @return {Vector3} A reference to this vector.
  4212. */
  4213. max( v ) {
  4214. this.x = Math.max( this.x, v.x );
  4215. this.y = Math.max( this.y, v.y );
  4216. this.z = Math.max( this.z, v.z );
  4217. return this;
  4218. }
  4219. /**
  4220. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4221. * value, it is replaced by the corresponding value.
  4222. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4223. * it is replaced by the corresponding value.
  4224. *
  4225. * @param {Vector3} min - The minimum x, y and z values.
  4226. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4227. * @return {Vector3} A reference to this vector.
  4228. */
  4229. clamp( min, max ) {
  4230. // assumes min < max, componentwise
  4231. this.x = clamp( this.x, min.x, max.x );
  4232. this.y = clamp( this.y, min.y, max.y );
  4233. this.z = clamp( this.z, min.z, max.z );
  4234. return this;
  4235. }
  4236. /**
  4237. * If this vector's x, y or z values are greater than the max value, they are
  4238. * replaced by the max value.
  4239. * If this vector's x, y or z values are less than the min value, they are
  4240. * replaced by the min value.
  4241. *
  4242. * @param {number} minVal - The minimum value the components will be clamped to.
  4243. * @param {number} maxVal - The maximum value the components will be clamped to.
  4244. * @return {Vector3} A reference to this vector.
  4245. */
  4246. clampScalar( minVal, maxVal ) {
  4247. this.x = clamp( this.x, minVal, maxVal );
  4248. this.y = clamp( this.y, minVal, maxVal );
  4249. this.z = clamp( this.z, minVal, maxVal );
  4250. return this;
  4251. }
  4252. /**
  4253. * If this vector's length is greater than the max value, it is replaced by
  4254. * the max value.
  4255. * If this vector's length is less than the min value, it is replaced by the
  4256. * min value.
  4257. *
  4258. * @param {number} min - The minimum value the vector length will be clamped to.
  4259. * @param {number} max - The maximum value the vector length will be clamped to.
  4260. * @return {Vector3} A reference to this vector.
  4261. */
  4262. clampLength( min, max ) {
  4263. const length = this.length();
  4264. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4265. }
  4266. /**
  4267. * The components of this vector are rounded down to the nearest integer value.
  4268. *
  4269. * @return {Vector3} A reference to this vector.
  4270. */
  4271. floor() {
  4272. this.x = Math.floor( this.x );
  4273. this.y = Math.floor( this.y );
  4274. this.z = Math.floor( this.z );
  4275. return this;
  4276. }
  4277. /**
  4278. * The components of this vector are rounded up to the nearest integer value.
  4279. *
  4280. * @return {Vector3} A reference to this vector.
  4281. */
  4282. ceil() {
  4283. this.x = Math.ceil( this.x );
  4284. this.y = Math.ceil( this.y );
  4285. this.z = Math.ceil( this.z );
  4286. return this;
  4287. }
  4288. /**
  4289. * The components of this vector are rounded to the nearest integer value
  4290. *
  4291. * @return {Vector3} A reference to this vector.
  4292. */
  4293. round() {
  4294. this.x = Math.round( this.x );
  4295. this.y = Math.round( this.y );
  4296. this.z = Math.round( this.z );
  4297. return this;
  4298. }
  4299. /**
  4300. * The components of this vector are rounded towards zero (up if negative,
  4301. * down if positive) to an integer value.
  4302. *
  4303. * @return {Vector3} A reference to this vector.
  4304. */
  4305. roundToZero() {
  4306. this.x = Math.trunc( this.x );
  4307. this.y = Math.trunc( this.y );
  4308. this.z = Math.trunc( this.z );
  4309. return this;
  4310. }
  4311. /**
  4312. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4313. *
  4314. * @return {Vector3} A reference to this vector.
  4315. */
  4316. negate() {
  4317. this.x = - this.x;
  4318. this.y = - this.y;
  4319. this.z = - this.z;
  4320. return this;
  4321. }
  4322. /**
  4323. * Calculates the dot product of the given vector with this instance.
  4324. *
  4325. * @param {Vector3} v - The vector to compute the dot product with.
  4326. * @return {number} The result of the dot product.
  4327. */
  4328. dot( v ) {
  4329. return this.x * v.x + this.y * v.y + this.z * v.z;
  4330. }
  4331. /**
  4332. * Computes the square of the Euclidean length (straight-line length) from
  4333. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4334. * compare the length squared instead as it is slightly more efficient to calculate.
  4335. *
  4336. * @return {number} The square length of this vector.
  4337. */
  4338. lengthSq() {
  4339. return this.x * this.x + this.y * this.y + this.z * this.z;
  4340. }
  4341. /**
  4342. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4343. *
  4344. * @return {number} The length of this vector.
  4345. */
  4346. length() {
  4347. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4348. }
  4349. /**
  4350. * Computes the Manhattan length of this vector.
  4351. *
  4352. * @return {number} The length of this vector.
  4353. */
  4354. manhattanLength() {
  4355. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4356. }
  4357. /**
  4358. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4359. * with the same direction as this one, but with a vector length of `1`.
  4360. *
  4361. * @return {Vector3} A reference to this vector.
  4362. */
  4363. normalize() {
  4364. return this.divideScalar( this.length() || 1 );
  4365. }
  4366. /**
  4367. * Sets this vector to a vector with the same direction as this one, but
  4368. * with the specified length.
  4369. *
  4370. * @param {number} length - The new length of this vector.
  4371. * @return {Vector3} A reference to this vector.
  4372. */
  4373. setLength( length ) {
  4374. return this.normalize().multiplyScalar( length );
  4375. }
  4376. /**
  4377. * Linearly interpolates between the given vector and this instance, where
  4378. * alpha is the percent distance along the line - alpha = 0 will be this
  4379. * vector, and alpha = 1 will be the given one.
  4380. *
  4381. * @param {Vector3} v - The vector to interpolate towards.
  4382. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4383. * @return {Vector3} A reference to this vector.
  4384. */
  4385. lerp( v, alpha ) {
  4386. this.x += ( v.x - this.x ) * alpha;
  4387. this.y += ( v.y - this.y ) * alpha;
  4388. this.z += ( v.z - this.z ) * alpha;
  4389. return this;
  4390. }
  4391. /**
  4392. * Linearly interpolates between the given vectors, where alpha is the percent
  4393. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4394. * be the second one. The result is stored in this instance.
  4395. *
  4396. * @param {Vector3} v1 - The first vector.
  4397. * @param {Vector3} v2 - The second vector.
  4398. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4399. * @return {Vector3} A reference to this vector.
  4400. */
  4401. lerpVectors( v1, v2, alpha ) {
  4402. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4403. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4404. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4405. return this;
  4406. }
  4407. /**
  4408. * Calculates the cross product of the given vector with this instance.
  4409. *
  4410. * @param {Vector3} v - The vector to compute the cross product with.
  4411. * @return {Vector3} The result of the cross product.
  4412. */
  4413. cross( v ) {
  4414. return this.crossVectors( this, v );
  4415. }
  4416. /**
  4417. * Calculates the cross product of the given vectors and stores the result
  4418. * in this instance.
  4419. *
  4420. * @param {Vector3} a - The first vector.
  4421. * @param {Vector3} b - The second vector.
  4422. * @return {Vector3} A reference to this vector.
  4423. */
  4424. crossVectors( a, b ) {
  4425. const ax = a.x, ay = a.y, az = a.z;
  4426. const bx = b.x, by = b.y, bz = b.z;
  4427. this.x = ay * bz - az * by;
  4428. this.y = az * bx - ax * bz;
  4429. this.z = ax * by - ay * bx;
  4430. return this;
  4431. }
  4432. /**
  4433. * Projects this vector onto the given one.
  4434. *
  4435. * @param {Vector3} v - The vector to project to.
  4436. * @return {Vector3} A reference to this vector.
  4437. */
  4438. projectOnVector( v ) {
  4439. const denominator = v.lengthSq();
  4440. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4441. const scalar = v.dot( this ) / denominator;
  4442. return this.copy( v ).multiplyScalar( scalar );
  4443. }
  4444. /**
  4445. * Projects this vector onto a plane by subtracting this
  4446. * vector projected onto the plane's normal from this vector.
  4447. *
  4448. * @param {Vector3} planeNormal - The plane normal.
  4449. * @return {Vector3} A reference to this vector.
  4450. */
  4451. projectOnPlane( planeNormal ) {
  4452. _vector$c.copy( this ).projectOnVector( planeNormal );
  4453. return this.sub( _vector$c );
  4454. }
  4455. /**
  4456. * Reflects this vector off a plane orthogonal to the given normal vector.
  4457. *
  4458. * @param {Vector3} normal - The (normalized) normal vector.
  4459. * @return {Vector3} A reference to this vector.
  4460. */
  4461. reflect( normal ) {
  4462. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4463. }
  4464. /**
  4465. * Returns the angle between the given vector and this instance in radians.
  4466. *
  4467. * @param {Vector3} v - The vector to compute the angle with.
  4468. * @return {number} The angle in radians.
  4469. */
  4470. angleTo( v ) {
  4471. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4472. if ( denominator === 0 ) return Math.PI / 2;
  4473. const theta = this.dot( v ) / denominator;
  4474. // clamp, to handle numerical problems
  4475. return Math.acos( clamp( theta, -1, 1 ) );
  4476. }
  4477. /**
  4478. * Computes the distance from the given vector to this instance.
  4479. *
  4480. * @param {Vector3} v - The vector to compute the distance to.
  4481. * @return {number} The distance.
  4482. */
  4483. distanceTo( v ) {
  4484. return Math.sqrt( this.distanceToSquared( v ) );
  4485. }
  4486. /**
  4487. * Computes the squared distance from the given vector to this instance.
  4488. * If you are just comparing the distance with another distance, you should compare
  4489. * the distance squared instead as it is slightly more efficient to calculate.
  4490. *
  4491. * @param {Vector3} v - The vector to compute the squared distance to.
  4492. * @return {number} The squared distance.
  4493. */
  4494. distanceToSquared( v ) {
  4495. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4496. return dx * dx + dy * dy + dz * dz;
  4497. }
  4498. /**
  4499. * Computes the Manhattan distance from the given vector to this instance.
  4500. *
  4501. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4502. * @return {number} The Manhattan distance.
  4503. */
  4504. manhattanDistanceTo( v ) {
  4505. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4506. }
  4507. /**
  4508. * Sets the vector components from the given spherical coordinates.
  4509. *
  4510. * @param {Spherical} s - The spherical coordinates.
  4511. * @return {Vector3} A reference to this vector.
  4512. */
  4513. setFromSpherical( s ) {
  4514. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4515. }
  4516. /**
  4517. * Sets the vector components from the given spherical coordinates.
  4518. *
  4519. * @param {number} radius - The radius.
  4520. * @param {number} phi - The phi angle in radians.
  4521. * @param {number} theta - The theta angle in radians.
  4522. * @return {Vector3} A reference to this vector.
  4523. */
  4524. setFromSphericalCoords( radius, phi, theta ) {
  4525. const sinPhiRadius = Math.sin( phi ) * radius;
  4526. this.x = sinPhiRadius * Math.sin( theta );
  4527. this.y = Math.cos( phi ) * radius;
  4528. this.z = sinPhiRadius * Math.cos( theta );
  4529. return this;
  4530. }
  4531. /**
  4532. * Sets the vector components from the given cylindrical coordinates.
  4533. *
  4534. * @param {Cylindrical} c - The cylindrical coordinates.
  4535. * @return {Vector3} A reference to this vector.
  4536. */
  4537. setFromCylindrical( c ) {
  4538. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4539. }
  4540. /**
  4541. * Sets the vector components from the given cylindrical coordinates.
  4542. *
  4543. * @param {number} radius - The radius.
  4544. * @param {number} theta - The theta angle in radians.
  4545. * @param {number} y - The y value.
  4546. * @return {Vector3} A reference to this vector.
  4547. */
  4548. setFromCylindricalCoords( radius, theta, y ) {
  4549. this.x = radius * Math.sin( theta );
  4550. this.y = y;
  4551. this.z = radius * Math.cos( theta );
  4552. return this;
  4553. }
  4554. /**
  4555. * Sets the vector components to the position elements of the
  4556. * given transformation matrix.
  4557. *
  4558. * @param {Matrix4} m - The 4x4 matrix.
  4559. * @return {Vector3} A reference to this vector.
  4560. */
  4561. setFromMatrixPosition( m ) {
  4562. const e = m.elements;
  4563. this.x = e[ 12 ];
  4564. this.y = e[ 13 ];
  4565. this.z = e[ 14 ];
  4566. return this;
  4567. }
  4568. /**
  4569. * Sets the vector components to the scale elements of the
  4570. * given transformation matrix.
  4571. *
  4572. * @param {Matrix4} m - The 4x4 matrix.
  4573. * @return {Vector3} A reference to this vector.
  4574. */
  4575. setFromMatrixScale( m ) {
  4576. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4577. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4578. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4579. this.x = sx;
  4580. this.y = sy;
  4581. this.z = sz;
  4582. return this;
  4583. }
  4584. /**
  4585. * Sets the vector components from the specified matrix column.
  4586. *
  4587. * @param {Matrix4} m - The 4x4 matrix.
  4588. * @param {number} index - The column index.
  4589. * @return {Vector3} A reference to this vector.
  4590. */
  4591. setFromMatrixColumn( m, index ) {
  4592. return this.fromArray( m.elements, index * 4 );
  4593. }
  4594. /**
  4595. * Sets the vector components from the specified matrix column.
  4596. *
  4597. * @param {Matrix3} m - The 3x3 matrix.
  4598. * @param {number} index - The column index.
  4599. * @return {Vector3} A reference to this vector.
  4600. */
  4601. setFromMatrix3Column( m, index ) {
  4602. return this.fromArray( m.elements, index * 3 );
  4603. }
  4604. /**
  4605. * Sets the vector components from the given Euler angles.
  4606. *
  4607. * @param {Euler} e - The Euler angles to set.
  4608. * @return {Vector3} A reference to this vector.
  4609. */
  4610. setFromEuler( e ) {
  4611. this.x = e._x;
  4612. this.y = e._y;
  4613. this.z = e._z;
  4614. return this;
  4615. }
  4616. /**
  4617. * Sets the vector components from the RGB components of the
  4618. * given color.
  4619. *
  4620. * @param {Color} c - The color to set.
  4621. * @return {Vector3} A reference to this vector.
  4622. */
  4623. setFromColor( c ) {
  4624. this.x = c.r;
  4625. this.y = c.g;
  4626. this.z = c.b;
  4627. return this;
  4628. }
  4629. /**
  4630. * Returns `true` if this vector is equal with the given one.
  4631. *
  4632. * @param {Vector3} v - The vector to test for equality.
  4633. * @return {boolean} Whether this vector is equal with the given one.
  4634. */
  4635. equals( v ) {
  4636. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4637. }
  4638. /**
  4639. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4640. * and z value to be `array[ offset + 2 ]`.
  4641. *
  4642. * @param {Array<number>} array - An array holding the vector component values.
  4643. * @param {number} [offset=0] - The offset into the array.
  4644. * @return {Vector3} A reference to this vector.
  4645. */
  4646. fromArray( array, offset = 0 ) {
  4647. this.x = array[ offset ];
  4648. this.y = array[ offset + 1 ];
  4649. this.z = array[ offset + 2 ];
  4650. return this;
  4651. }
  4652. /**
  4653. * Writes the components of this vector to the given array. If no array is provided,
  4654. * the method returns a new instance.
  4655. *
  4656. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4657. * @param {number} [offset=0] - Index of the first element in the array.
  4658. * @return {Array<number>} The vector components.
  4659. */
  4660. toArray( array = [], offset = 0 ) {
  4661. array[ offset ] = this.x;
  4662. array[ offset + 1 ] = this.y;
  4663. array[ offset + 2 ] = this.z;
  4664. return array;
  4665. }
  4666. /**
  4667. * Sets the components of this vector from the given buffer attribute.
  4668. *
  4669. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4670. * @param {number} index - The index into the attribute.
  4671. * @return {Vector3} A reference to this vector.
  4672. */
  4673. fromBufferAttribute( attribute, index ) {
  4674. this.x = attribute.getX( index );
  4675. this.y = attribute.getY( index );
  4676. this.z = attribute.getZ( index );
  4677. return this;
  4678. }
  4679. /**
  4680. * Sets each component of this vector to a pseudo-random value between `0` and
  4681. * `1`, excluding `1`.
  4682. *
  4683. * @return {Vector3} A reference to this vector.
  4684. */
  4685. random() {
  4686. this.x = Math.random();
  4687. this.y = Math.random();
  4688. this.z = Math.random();
  4689. return this;
  4690. }
  4691. /**
  4692. * Sets this vector to a uniformly random point on a unit sphere.
  4693. *
  4694. * @return {Vector3} A reference to this vector.
  4695. */
  4696. randomDirection() {
  4697. // https://mathworld.wolfram.com/SpherePointPicking.html
  4698. const theta = Math.random() * Math.PI * 2;
  4699. const u = Math.random() * 2 - 1;
  4700. const c = Math.sqrt( 1 - u * u );
  4701. this.x = c * Math.cos( theta );
  4702. this.y = u;
  4703. this.z = c * Math.sin( theta );
  4704. return this;
  4705. }
  4706. *[ Symbol.iterator ]() {
  4707. yield this.x;
  4708. yield this.y;
  4709. yield this.z;
  4710. }
  4711. }
  4712. const _vector$c = /*@__PURE__*/ new Vector3();
  4713. const _quaternion$5 = /*@__PURE__*/ new Quaternion();
  4714. /**
  4715. * Represents a 3x3 matrix.
  4716. *
  4717. * A Note on Row-Major and Column-Major Ordering:
  4718. *
  4719. * The constructor and {@link Matrix3#set} method take arguments in
  4720. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4721. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4722. * This means that calling:
  4723. * ```js
  4724. * const m = new THREE.Matrix();
  4725. * m.set( 11, 12, 13,
  4726. * 21, 22, 23,
  4727. * 31, 32, 33 );
  4728. * ```
  4729. * will result in the elements array containing:
  4730. * ```js
  4731. * m.elements = [ 11, 21, 31,
  4732. * 12, 22, 32,
  4733. * 13, 23, 33 ];
  4734. * ```
  4735. * and internally all calculations are performed using column-major ordering.
  4736. * However, as the actual ordering makes no difference mathematically and
  4737. * most people are used to thinking about matrices in row-major order, the
  4738. * three.js documentation shows matrices in row-major order. Just bear in
  4739. * mind that if you are reading the source code, you'll have to take the
  4740. * transpose of any matrices outlined here to make sense of the calculations.
  4741. */
  4742. class Matrix3 {
  4743. /**
  4744. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4745. * in row-major order. If no arguments are provided, the constructor
  4746. * initializes the matrix as an identity matrix.
  4747. *
  4748. * @param {number} [n11] - 1-1 matrix element.
  4749. * @param {number} [n12] - 1-2 matrix element.
  4750. * @param {number} [n13] - 1-3 matrix element.
  4751. * @param {number} [n21] - 2-1 matrix element.
  4752. * @param {number} [n22] - 2-2 matrix element.
  4753. * @param {number} [n23] - 2-3 matrix element.
  4754. * @param {number} [n31] - 3-1 matrix element.
  4755. * @param {number} [n32] - 3-2 matrix element.
  4756. * @param {number} [n33] - 3-3 matrix element.
  4757. */
  4758. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4759. /**
  4760. * This flag can be used for type testing.
  4761. *
  4762. * @type {boolean}
  4763. * @readonly
  4764. * @default true
  4765. */
  4766. Matrix3.prototype.isMatrix3 = true;
  4767. /**
  4768. * A column-major list of matrix values.
  4769. *
  4770. * @type {Array<number>}
  4771. */
  4772. this.elements = [
  4773. 1, 0, 0,
  4774. 0, 1, 0,
  4775. 0, 0, 1
  4776. ];
  4777. if ( n11 !== undefined ) {
  4778. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4779. }
  4780. }
  4781. /**
  4782. * Sets the elements of the matrix.The arguments are supposed to be
  4783. * in row-major order.
  4784. *
  4785. * @param {number} [n11] - 1-1 matrix element.
  4786. * @param {number} [n12] - 1-2 matrix element.
  4787. * @param {number} [n13] - 1-3 matrix element.
  4788. * @param {number} [n21] - 2-1 matrix element.
  4789. * @param {number} [n22] - 2-2 matrix element.
  4790. * @param {number} [n23] - 2-3 matrix element.
  4791. * @param {number} [n31] - 3-1 matrix element.
  4792. * @param {number} [n32] - 3-2 matrix element.
  4793. * @param {number} [n33] - 3-3 matrix element.
  4794. * @return {Matrix3} A reference to this matrix.
  4795. */
  4796. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4797. const te = this.elements;
  4798. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4799. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4800. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4801. return this;
  4802. }
  4803. /**
  4804. * Sets this matrix to the 3x3 identity matrix.
  4805. *
  4806. * @return {Matrix3} A reference to this matrix.
  4807. */
  4808. identity() {
  4809. this.set(
  4810. 1, 0, 0,
  4811. 0, 1, 0,
  4812. 0, 0, 1
  4813. );
  4814. return this;
  4815. }
  4816. /**
  4817. * Copies the values of the given matrix to this instance.
  4818. *
  4819. * @param {Matrix3} m - The matrix to copy.
  4820. * @return {Matrix3} A reference to this matrix.
  4821. */
  4822. copy( m ) {
  4823. const te = this.elements;
  4824. const me = m.elements;
  4825. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4826. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4827. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4828. return this;
  4829. }
  4830. /**
  4831. * Extracts the basis of this matrix into the three axis vectors provided.
  4832. *
  4833. * @param {Vector3} xAxis - The basis's x axis.
  4834. * @param {Vector3} yAxis - The basis's y axis.
  4835. * @param {Vector3} zAxis - The basis's z axis.
  4836. * @return {Matrix3} A reference to this matrix.
  4837. */
  4838. extractBasis( xAxis, yAxis, zAxis ) {
  4839. xAxis.setFromMatrix3Column( this, 0 );
  4840. yAxis.setFromMatrix3Column( this, 1 );
  4841. zAxis.setFromMatrix3Column( this, 2 );
  4842. return this;
  4843. }
  4844. /**
  4845. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4846. *
  4847. * @param {Matrix4} m - The 4x4 matrix.
  4848. * @return {Matrix3} A reference to this matrix.
  4849. */
  4850. setFromMatrix4( m ) {
  4851. const me = m.elements;
  4852. this.set(
  4853. me[ 0 ], me[ 4 ], me[ 8 ],
  4854. me[ 1 ], me[ 5 ], me[ 9 ],
  4855. me[ 2 ], me[ 6 ], me[ 10 ]
  4856. );
  4857. return this;
  4858. }
  4859. /**
  4860. * Post-multiplies this matrix by the given 3x3 matrix.
  4861. *
  4862. * @param {Matrix3} m - The matrix to multiply with.
  4863. * @return {Matrix3} A reference to this matrix.
  4864. */
  4865. multiply( m ) {
  4866. return this.multiplyMatrices( this, m );
  4867. }
  4868. /**
  4869. * Pre-multiplies this matrix by the given 3x3 matrix.
  4870. *
  4871. * @param {Matrix3} m - The matrix to multiply with.
  4872. * @return {Matrix3} A reference to this matrix.
  4873. */
  4874. premultiply( m ) {
  4875. return this.multiplyMatrices( m, this );
  4876. }
  4877. /**
  4878. * Multiples the given 3x3 matrices and stores the result
  4879. * in this matrix.
  4880. *
  4881. * @param {Matrix3} a - The first matrix.
  4882. * @param {Matrix3} b - The second matrix.
  4883. * @return {Matrix3} A reference to this matrix.
  4884. */
  4885. multiplyMatrices( a, b ) {
  4886. const ae = a.elements;
  4887. const be = b.elements;
  4888. const te = this.elements;
  4889. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4890. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4891. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4892. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4893. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4894. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4895. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4896. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4897. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4898. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4899. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4900. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4901. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4902. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4903. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4904. return this;
  4905. }
  4906. /**
  4907. * Multiplies every component of the matrix by the given scalar.
  4908. *
  4909. * @param {number} s - The scalar.
  4910. * @return {Matrix3} A reference to this matrix.
  4911. */
  4912. multiplyScalar( s ) {
  4913. const te = this.elements;
  4914. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4915. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4916. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4917. return this;
  4918. }
  4919. /**
  4920. * Computes and returns the determinant of this matrix.
  4921. *
  4922. * @return {number} The determinant.
  4923. */
  4924. determinant() {
  4925. const te = this.elements;
  4926. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4927. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4928. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4929. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4930. }
  4931. /**
  4932. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4933. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4934. * a zero matrix instead.
  4935. *
  4936. * @return {Matrix3} A reference to this matrix.
  4937. */
  4938. invert() {
  4939. const te = this.elements,
  4940. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4941. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4942. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4943. t11 = n33 * n22 - n32 * n23,
  4944. t12 = n32 * n13 - n33 * n12,
  4945. t13 = n23 * n12 - n22 * n13,
  4946. det = n11 * t11 + n21 * t12 + n31 * t13;
  4947. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4948. const detInv = 1 / det;
  4949. te[ 0 ] = t11 * detInv;
  4950. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4951. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4952. te[ 3 ] = t12 * detInv;
  4953. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4954. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4955. te[ 6 ] = t13 * detInv;
  4956. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4957. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4958. return this;
  4959. }
  4960. /**
  4961. * Transposes this matrix in place.
  4962. *
  4963. * @return {Matrix3} A reference to this matrix.
  4964. */
  4965. transpose() {
  4966. let tmp;
  4967. const m = this.elements;
  4968. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4969. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4970. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4971. return this;
  4972. }
  4973. /**
  4974. * Computes the normal matrix which is the inverse transpose of the upper
  4975. * left 3x3 portion of the given 4x4 matrix.
  4976. *
  4977. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4978. * @return {Matrix3} A reference to this matrix.
  4979. */
  4980. getNormalMatrix( matrix4 ) {
  4981. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4982. }
  4983. /**
  4984. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4985. *
  4986. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4987. * @return {Matrix3} A reference to this matrix.
  4988. */
  4989. transposeIntoArray( r ) {
  4990. const m = this.elements;
  4991. r[ 0 ] = m[ 0 ];
  4992. r[ 1 ] = m[ 3 ];
  4993. r[ 2 ] = m[ 6 ];
  4994. r[ 3 ] = m[ 1 ];
  4995. r[ 4 ] = m[ 4 ];
  4996. r[ 5 ] = m[ 7 ];
  4997. r[ 6 ] = m[ 2 ];
  4998. r[ 7 ] = m[ 5 ];
  4999. r[ 8 ] = m[ 8 ];
  5000. return this;
  5001. }
  5002. /**
  5003. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  5004. *
  5005. * @param {number} tx - Offset x.
  5006. * @param {number} ty - Offset y.
  5007. * @param {number} sx - Repeat x.
  5008. * @param {number} sy - Repeat y.
  5009. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  5010. * @param {number} cx - Center x of rotation.
  5011. * @param {number} cy - Center y of rotation
  5012. * @return {Matrix3} A reference to this matrix.
  5013. */
  5014. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  5015. const c = Math.cos( rotation );
  5016. const s = Math.sin( rotation );
  5017. this.set(
  5018. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  5019. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  5020. 0, 0, 1
  5021. );
  5022. return this;
  5023. }
  5024. /**
  5025. * Scales this matrix with the given scalar values.
  5026. *
  5027. * @param {number} sx - The amount to scale in the X axis.
  5028. * @param {number} sy - The amount to scale in the Y axis.
  5029. * @return {Matrix3} A reference to this matrix.
  5030. */
  5031. scale( sx, sy ) {
  5032. this.premultiply( _m3.makeScale( sx, sy ) );
  5033. return this;
  5034. }
  5035. /**
  5036. * Rotates this matrix by the given angle.
  5037. *
  5038. * @param {number} theta - The rotation in radians.
  5039. * @return {Matrix3} A reference to this matrix.
  5040. */
  5041. rotate( theta ) {
  5042. this.premultiply( _m3.makeRotation( - theta ) );
  5043. return this;
  5044. }
  5045. /**
  5046. * Translates this matrix by the given scalar values.
  5047. *
  5048. * @param {number} tx - The amount to translate in the X axis.
  5049. * @param {number} ty - The amount to translate in the Y axis.
  5050. * @return {Matrix3} A reference to this matrix.
  5051. */
  5052. translate( tx, ty ) {
  5053. this.premultiply( _m3.makeTranslation( tx, ty ) );
  5054. return this;
  5055. }
  5056. // for 2D Transforms
  5057. /**
  5058. * Sets this matrix as a 2D translation transform.
  5059. *
  5060. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  5061. * @param {number} y - The amount to translate in the Y axis.
  5062. * @return {Matrix3} A reference to this matrix.
  5063. */
  5064. makeTranslation( x, y ) {
  5065. if ( x.isVector2 ) {
  5066. this.set(
  5067. 1, 0, x.x,
  5068. 0, 1, x.y,
  5069. 0, 0, 1
  5070. );
  5071. } else {
  5072. this.set(
  5073. 1, 0, x,
  5074. 0, 1, y,
  5075. 0, 0, 1
  5076. );
  5077. }
  5078. return this;
  5079. }
  5080. /**
  5081. * Sets this matrix as a 2D rotational transformation.
  5082. *
  5083. * @param {number} theta - The rotation in radians.
  5084. * @return {Matrix3} A reference to this matrix.
  5085. */
  5086. makeRotation( theta ) {
  5087. // counterclockwise
  5088. const c = Math.cos( theta );
  5089. const s = Math.sin( theta );
  5090. this.set(
  5091. c, - s, 0,
  5092. s, c, 0,
  5093. 0, 0, 1
  5094. );
  5095. return this;
  5096. }
  5097. /**
  5098. * Sets this matrix as a 2D scale transform.
  5099. *
  5100. * @param {number} x - The amount to scale in the X axis.
  5101. * @param {number} y - The amount to scale in the Y axis.
  5102. * @return {Matrix3} A reference to this matrix.
  5103. */
  5104. makeScale( x, y ) {
  5105. this.set(
  5106. x, 0, 0,
  5107. 0, y, 0,
  5108. 0, 0, 1
  5109. );
  5110. return this;
  5111. }
  5112. /**
  5113. * Returns `true` if this matrix is equal with the given one.
  5114. *
  5115. * @param {Matrix3} matrix - The matrix to test for equality.
  5116. * @return {boolean} Whether this matrix is equal with the given one.
  5117. */
  5118. equals( matrix ) {
  5119. const te = this.elements;
  5120. const me = matrix.elements;
  5121. for ( let i = 0; i < 9; i ++ ) {
  5122. if ( te[ i ] !== me[ i ] ) return false;
  5123. }
  5124. return true;
  5125. }
  5126. /**
  5127. * Sets the elements of the matrix from the given array.
  5128. *
  5129. * @param {Array<number>} array - The matrix elements in column-major order.
  5130. * @param {number} [offset=0] - Index of the first element in the array.
  5131. * @return {Matrix3} A reference to this matrix.
  5132. */
  5133. fromArray( array, offset = 0 ) {
  5134. for ( let i = 0; i < 9; i ++ ) {
  5135. this.elements[ i ] = array[ i + offset ];
  5136. }
  5137. return this;
  5138. }
  5139. /**
  5140. * Writes the elements of this matrix to the given array. If no array is provided,
  5141. * the method returns a new instance.
  5142. *
  5143. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  5144. * @param {number} [offset=0] - Index of the first element in the array.
  5145. * @return {Array<number>} The matrix elements in column-major order.
  5146. */
  5147. toArray( array = [], offset = 0 ) {
  5148. const te = this.elements;
  5149. array[ offset ] = te[ 0 ];
  5150. array[ offset + 1 ] = te[ 1 ];
  5151. array[ offset + 2 ] = te[ 2 ];
  5152. array[ offset + 3 ] = te[ 3 ];
  5153. array[ offset + 4 ] = te[ 4 ];
  5154. array[ offset + 5 ] = te[ 5 ];
  5155. array[ offset + 6 ] = te[ 6 ];
  5156. array[ offset + 7 ] = te[ 7 ];
  5157. array[ offset + 8 ] = te[ 8 ];
  5158. return array;
  5159. }
  5160. /**
  5161. * Returns a matrix with copied values from this instance.
  5162. *
  5163. * @return {Matrix3} A clone of this instance.
  5164. */
  5165. clone() {
  5166. return new this.constructor().fromArray( this.elements );
  5167. }
  5168. }
  5169. const _m3 = /*@__PURE__*/ new Matrix3();
  5170. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5171. 0.4123908, 0.3575843, 0.1804808,
  5172. 0.2126390, 0.7151687, 0.0721923,
  5173. 0.0193308, 0.1191948, 0.9505322
  5174. );
  5175. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5176. 3.2409699, -1.5373832, -0.4986108,
  5177. -0.9692436, 1.8759675, 0.0415551,
  5178. 0.0556301, -0.203977, 1.0569715
  5179. );
  5180. function createColorManagement() {
  5181. const ColorManagement = {
  5182. enabled: true,
  5183. workingColorSpace: LinearSRGBColorSpace,
  5184. /**
  5185. * Implementations of supported color spaces.
  5186. *
  5187. * Required:
  5188. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5189. * - whitePoint: reference white [ x y ]
  5190. * - transfer: transfer function (pre-defined)
  5191. * - toXYZ: Matrix3 RGB to XYZ transform
  5192. * - fromXYZ: Matrix3 XYZ to RGB transform
  5193. * - luminanceCoefficients: RGB luminance coefficients
  5194. *
  5195. * Optional:
  5196. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5197. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5198. *
  5199. * Reference:
  5200. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5201. */
  5202. spaces: {},
  5203. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5204. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5205. return color;
  5206. }
  5207. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5208. color.r = SRGBToLinear( color.r );
  5209. color.g = SRGBToLinear( color.g );
  5210. color.b = SRGBToLinear( color.b );
  5211. }
  5212. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5213. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5214. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5215. }
  5216. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5217. color.r = LinearToSRGB( color.r );
  5218. color.g = LinearToSRGB( color.g );
  5219. color.b = LinearToSRGB( color.b );
  5220. }
  5221. return color;
  5222. },
  5223. workingToColorSpace: function ( color, targetColorSpace ) {
  5224. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5225. },
  5226. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5227. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5228. },
  5229. getPrimaries: function ( colorSpace ) {
  5230. return this.spaces[ colorSpace ].primaries;
  5231. },
  5232. getTransfer: function ( colorSpace ) {
  5233. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5234. return this.spaces[ colorSpace ].transfer;
  5235. },
  5236. getToneMappingMode: function ( colorSpace ) {
  5237. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5238. },
  5239. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5240. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5241. },
  5242. define: function ( colorSpaces ) {
  5243. Object.assign( this.spaces, colorSpaces );
  5244. },
  5245. // Internal APIs
  5246. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5247. return targetMatrix
  5248. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5249. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5250. },
  5251. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5252. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5253. },
  5254. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5255. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5256. },
  5257. // Deprecated
  5258. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5259. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5260. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5261. },
  5262. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5263. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5264. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5265. },
  5266. };
  5267. /******************************************************************************
  5268. * sRGB definitions
  5269. */
  5270. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5271. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5272. const D65 = [ 0.3127, 0.3290 ];
  5273. ColorManagement.define( {
  5274. [ LinearSRGBColorSpace ]: {
  5275. primaries: REC709_PRIMARIES,
  5276. whitePoint: D65,
  5277. transfer: LinearTransfer,
  5278. toXYZ: LINEAR_REC709_TO_XYZ,
  5279. fromXYZ: XYZ_TO_LINEAR_REC709,
  5280. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5281. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5282. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5283. },
  5284. [ SRGBColorSpace ]: {
  5285. primaries: REC709_PRIMARIES,
  5286. whitePoint: D65,
  5287. transfer: SRGBTransfer,
  5288. toXYZ: LINEAR_REC709_TO_XYZ,
  5289. fromXYZ: XYZ_TO_LINEAR_REC709,
  5290. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5291. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5292. },
  5293. } );
  5294. return ColorManagement;
  5295. }
  5296. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5297. function SRGBToLinear( c ) {
  5298. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5299. }
  5300. function LinearToSRGB( c ) {
  5301. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5302. }
  5303. let _canvas;
  5304. /**
  5305. * A class containing utility functions for images.
  5306. *
  5307. * @hideconstructor
  5308. */
  5309. class ImageUtils {
  5310. /**
  5311. * Returns a data URI containing a representation of the given image.
  5312. *
  5313. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5314. * @param {string} [type='image/png'] - Indicates the image format.
  5315. * @return {string} The data URI.
  5316. */
  5317. static getDataURL( image, type = 'image/png' ) {
  5318. if ( /^data:/i.test( image.src ) ) {
  5319. return image.src;
  5320. }
  5321. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5322. return image.src;
  5323. }
  5324. let canvas;
  5325. if ( image instanceof HTMLCanvasElement ) {
  5326. canvas = image;
  5327. } else {
  5328. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5329. _canvas.width = image.width;
  5330. _canvas.height = image.height;
  5331. const context = _canvas.getContext( '2d' );
  5332. if ( image instanceof ImageData ) {
  5333. context.putImageData( image, 0, 0 );
  5334. } else {
  5335. context.drawImage( image, 0, 0, image.width, image.height );
  5336. }
  5337. canvas = _canvas;
  5338. }
  5339. return canvas.toDataURL( type );
  5340. }
  5341. /**
  5342. * Converts the given sRGB image data to linear color space.
  5343. *
  5344. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5345. * @return {HTMLCanvasElement|Object} The converted image.
  5346. */
  5347. static sRGBToLinear( image ) {
  5348. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5349. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5350. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5351. const canvas = createElementNS( 'canvas' );
  5352. canvas.width = image.width;
  5353. canvas.height = image.height;
  5354. const context = canvas.getContext( '2d' );
  5355. context.drawImage( image, 0, 0, image.width, image.height );
  5356. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5357. const data = imageData.data;
  5358. for ( let i = 0; i < data.length; i ++ ) {
  5359. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5360. }
  5361. context.putImageData( imageData, 0, 0 );
  5362. return canvas;
  5363. } else if ( image.data ) {
  5364. const data = image.data.slice( 0 );
  5365. for ( let i = 0; i < data.length; i ++ ) {
  5366. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5367. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5368. } else {
  5369. // assuming float
  5370. data[ i ] = SRGBToLinear( data[ i ] );
  5371. }
  5372. }
  5373. return {
  5374. data: data,
  5375. width: image.width,
  5376. height: image.height
  5377. };
  5378. } else {
  5379. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5380. return image;
  5381. }
  5382. }
  5383. }
  5384. let _sourceId = 0;
  5385. /**
  5386. * Represents the data source of a texture.
  5387. *
  5388. * The main purpose of this class is to decouple the data definition from the texture
  5389. * definition so the same data can be used with multiple texture instances.
  5390. */
  5391. class Source {
  5392. /**
  5393. * Constructs a new video texture.
  5394. *
  5395. * @param {any} [data=null] - The data definition of a texture.
  5396. */
  5397. constructor( data = null ) {
  5398. /**
  5399. * This flag can be used for type testing.
  5400. *
  5401. * @type {boolean}
  5402. * @readonly
  5403. * @default true
  5404. */
  5405. this.isSource = true;
  5406. /**
  5407. * The ID of the source.
  5408. *
  5409. * @name Source#id
  5410. * @type {number}
  5411. * @readonly
  5412. */
  5413. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5414. /**
  5415. * The UUID of the source.
  5416. *
  5417. * @type {string}
  5418. * @readonly
  5419. */
  5420. this.uuid = generateUUID();
  5421. /**
  5422. * The data definition of a texture.
  5423. *
  5424. * @type {any}
  5425. */
  5426. this.data = data;
  5427. /**
  5428. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5429. * provides more control on how texture data should be processed. When `dataReady` is set
  5430. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5431. * the data into the GPU memory.
  5432. *
  5433. * @type {boolean}
  5434. * @default true
  5435. */
  5436. this.dataReady = true;
  5437. /**
  5438. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5439. *
  5440. * @type {number}
  5441. * @readonly
  5442. * @default 0
  5443. */
  5444. this.version = 0;
  5445. }
  5446. /**
  5447. * Returns the dimensions of the source into the given target vector.
  5448. *
  5449. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5450. * @return {(Vector2|Vector3)} The dimensions of the source.
  5451. */
  5452. getSize( target ) {
  5453. const data = this.data;
  5454. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5455. target.set( data.videoWidth, data.videoHeight, 0 );
  5456. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5457. target.set( data.displayHeight, data.displayWidth, 0 );
  5458. } else if ( data !== null ) {
  5459. target.set( data.width, data.height, data.depth || 0 );
  5460. } else {
  5461. target.set( 0, 0, 0 );
  5462. }
  5463. return target;
  5464. }
  5465. /**
  5466. * When the property is set to `true`, the engine allocates the memory
  5467. * for the texture (if necessary) and triggers the actual texture upload
  5468. * to the GPU next time the source is used.
  5469. *
  5470. * @type {boolean}
  5471. * @default false
  5472. * @param {boolean} value
  5473. */
  5474. set needsUpdate( value ) {
  5475. if ( value === true ) this.version ++;
  5476. }
  5477. /**
  5478. * Serializes the source into JSON.
  5479. *
  5480. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5481. * @return {Object} A JSON object representing the serialized source.
  5482. * @see {@link ObjectLoader#parse}
  5483. */
  5484. toJSON( meta ) {
  5485. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5486. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5487. return meta.images[ this.uuid ];
  5488. }
  5489. const output = {
  5490. uuid: this.uuid,
  5491. url: ''
  5492. };
  5493. const data = this.data;
  5494. if ( data !== null ) {
  5495. let url;
  5496. if ( Array.isArray( data ) ) {
  5497. // cube texture
  5498. url = [];
  5499. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5500. if ( data[ i ].isDataTexture ) {
  5501. url.push( serializeImage( data[ i ].image ) );
  5502. } else {
  5503. url.push( serializeImage( data[ i ] ) );
  5504. }
  5505. }
  5506. } else {
  5507. // texture
  5508. url = serializeImage( data );
  5509. }
  5510. output.url = url;
  5511. }
  5512. if ( ! isRootObject ) {
  5513. meta.images[ this.uuid ] = output;
  5514. }
  5515. return output;
  5516. }
  5517. }
  5518. function serializeImage( image ) {
  5519. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5520. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5521. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5522. // default images
  5523. return ImageUtils.getDataURL( image );
  5524. } else {
  5525. if ( image.data ) {
  5526. // images of DataTexture
  5527. return {
  5528. data: Array.from( image.data ),
  5529. width: image.width,
  5530. height: image.height,
  5531. type: image.data.constructor.name
  5532. };
  5533. } else {
  5534. warn( 'Texture: Unable to serialize Texture.' );
  5535. return {};
  5536. }
  5537. }
  5538. }
  5539. let _textureId = 0;
  5540. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5541. /**
  5542. * Base class for all textures.
  5543. *
  5544. * Note: After the initial use of a texture, its dimensions, format, and type
  5545. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5546. *
  5547. * @augments EventDispatcher
  5548. */
  5549. class Texture extends EventDispatcher {
  5550. /**
  5551. * Constructs a new texture.
  5552. *
  5553. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5554. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5555. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5556. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5557. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5558. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5559. * @param {number} [format=RGBAFormat] - The texture format.
  5560. * @param {number} [type=UnsignedByteType] - The texture type.
  5561. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5562. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5563. */
  5564. 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 ) {
  5565. super();
  5566. /**
  5567. * This flag can be used for type testing.
  5568. *
  5569. * @type {boolean}
  5570. * @readonly
  5571. * @default true
  5572. */
  5573. this.isTexture = true;
  5574. /**
  5575. * The ID of the texture.
  5576. *
  5577. * @name Texture#id
  5578. * @type {number}
  5579. * @readonly
  5580. */
  5581. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5582. /**
  5583. * The UUID of the texture.
  5584. *
  5585. * @type {string}
  5586. * @readonly
  5587. */
  5588. this.uuid = generateUUID();
  5589. /**
  5590. * The name of the texture.
  5591. *
  5592. * @type {string}
  5593. */
  5594. this.name = '';
  5595. /**
  5596. * The data definition of a texture. A reference to the data source can be
  5597. * shared across textures. This is often useful in context of spritesheets
  5598. * where multiple textures render the same data but with different texture
  5599. * transformations.
  5600. *
  5601. * @type {Source}
  5602. */
  5603. this.source = new Source( image );
  5604. /**
  5605. * An array holding user-defined mipmaps.
  5606. *
  5607. * @type {Array<Object>}
  5608. */
  5609. this.mipmaps = [];
  5610. /**
  5611. * How the texture is applied to the object. The value `UVMapping`
  5612. * is the default, where texture or uv coordinates are used to apply the map.
  5613. *
  5614. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5615. * @default UVMapping
  5616. */
  5617. this.mapping = mapping;
  5618. /**
  5619. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5620. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5621. *
  5622. * @type {number}
  5623. * @default 0
  5624. */
  5625. this.channel = 0;
  5626. /**
  5627. * This defines how the texture is wrapped horizontally and corresponds to
  5628. * *U* in UV mapping.
  5629. *
  5630. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5631. * @default ClampToEdgeWrapping
  5632. */
  5633. this.wrapS = wrapS;
  5634. /**
  5635. * This defines how the texture is wrapped horizontally and corresponds to
  5636. * *V* in UV mapping.
  5637. *
  5638. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5639. * @default ClampToEdgeWrapping
  5640. */
  5641. this.wrapT = wrapT;
  5642. /**
  5643. * How the texture is sampled when a texel covers more than one pixel.
  5644. *
  5645. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5646. * @default LinearFilter
  5647. */
  5648. this.magFilter = magFilter;
  5649. /**
  5650. * How the texture is sampled when a texel covers less than one pixel.
  5651. *
  5652. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5653. * @default LinearMipmapLinearFilter
  5654. */
  5655. this.minFilter = minFilter;
  5656. /**
  5657. * The number of samples taken along the axis through the pixel that has the
  5658. * highest density of texels. By default, this value is `1`. A higher value
  5659. * gives a less blurry result than a basic mipmap, at the cost of more
  5660. * texture samples being used.
  5661. *
  5662. * @type {number}
  5663. * @default Texture.DEFAULT_ANISOTROPY
  5664. */
  5665. this.anisotropy = anisotropy;
  5666. /**
  5667. * The format of the texture.
  5668. *
  5669. * @type {number}
  5670. * @default RGBAFormat
  5671. */
  5672. this.format = format;
  5673. /**
  5674. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5675. * defines how the texture data is going to be stored on the GPU.
  5676. *
  5677. * This property allows to overwrite the default format.
  5678. *
  5679. * @type {?string}
  5680. * @default null
  5681. */
  5682. this.internalFormat = null;
  5683. /**
  5684. * The data type of the texture.
  5685. *
  5686. * @type {number}
  5687. * @default UnsignedByteType
  5688. */
  5689. this.type = type;
  5690. /**
  5691. * How much a single repetition of the texture is offset from the beginning,
  5692. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5693. *
  5694. * @type {Vector2}
  5695. * @default (0,0)
  5696. */
  5697. this.offset = new Vector2( 0, 0 );
  5698. /**
  5699. * How many times the texture is repeated across the surface, in each
  5700. * direction U and V. If repeat is set greater than `1` in either direction,
  5701. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5702. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5703. *
  5704. * @type {Vector2}
  5705. * @default (1,1)
  5706. */
  5707. this.repeat = new Vector2( 1, 1 );
  5708. /**
  5709. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5710. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5711. *
  5712. * @type {Vector2}
  5713. * @default (0,0)
  5714. */
  5715. this.center = new Vector2( 0, 0 );
  5716. /**
  5717. * How much the texture is rotated around the center point, in radians.
  5718. * Positive values are counter-clockwise.
  5719. *
  5720. * @type {number}
  5721. * @default 0
  5722. */
  5723. this.rotation = 0;
  5724. /**
  5725. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5726. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5727. * {@link Texture#rotation}, and {@link Texture#center}.
  5728. *
  5729. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5730. *
  5731. * @type {boolean}
  5732. * @default true
  5733. */
  5734. this.matrixAutoUpdate = true;
  5735. /**
  5736. * The uv-transformation matrix of the texture.
  5737. *
  5738. * @type {Matrix3}
  5739. */
  5740. this.matrix = new Matrix3();
  5741. /**
  5742. * Whether to generate mipmaps (if possible) for a texture.
  5743. *
  5744. * Set this to `false` if you are creating mipmaps manually.
  5745. *
  5746. * @type {boolean}
  5747. * @default true
  5748. */
  5749. this.generateMipmaps = true;
  5750. /**
  5751. * If set to `true`, the alpha channel, if present, is multiplied into the
  5752. * color channels when the texture is uploaded to the GPU.
  5753. *
  5754. * Note that this property has no effect when using `ImageBitmap`. You need to
  5755. * configure premultiply alpha on bitmap creation instead.
  5756. *
  5757. * @type {boolean}
  5758. * @default false
  5759. */
  5760. this.premultiplyAlpha = false;
  5761. /**
  5762. * If set to `true`, the texture is flipped along the vertical axis when
  5763. * uploaded to the GPU.
  5764. *
  5765. * Note that this property has no effect when using `ImageBitmap`. You need to
  5766. * configure the flip on bitmap creation instead.
  5767. *
  5768. * @type {boolean}
  5769. * @default true
  5770. */
  5771. this.flipY = true;
  5772. /**
  5773. * Specifies the alignment requirements for the start of each pixel row in memory.
  5774. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5775. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5776. *
  5777. * @type {number}
  5778. * @default 4
  5779. */
  5780. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5781. /**
  5782. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5783. *
  5784. * @type {string}
  5785. * @default NoColorSpace
  5786. */
  5787. this.colorSpace = colorSpace;
  5788. /**
  5789. * An object that can be used to store custom data about the texture. It
  5790. * should not hold references to functions as these will not be cloned.
  5791. *
  5792. * @type {Object}
  5793. */
  5794. this.userData = {};
  5795. /**
  5796. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5797. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5798. *
  5799. * @type {Array<Object>}
  5800. */
  5801. this.updateRanges = [];
  5802. /**
  5803. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5804. *
  5805. * @type {number}
  5806. * @readonly
  5807. * @default 0
  5808. */
  5809. this.version = 0;
  5810. /**
  5811. * A callback function, called when the texture is updated (e.g., when
  5812. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5813. *
  5814. * @type {?Function}
  5815. * @default null
  5816. */
  5817. this.onUpdate = null;
  5818. /**
  5819. * An optional back reference to the textures render target.
  5820. *
  5821. * @type {?(RenderTarget|WebGLRenderTarget)}
  5822. * @default null
  5823. */
  5824. this.renderTarget = null;
  5825. /**
  5826. * Indicates whether a texture belongs to a render target or not.
  5827. *
  5828. * @type {boolean}
  5829. * @readonly
  5830. * @default false
  5831. */
  5832. this.isRenderTargetTexture = false;
  5833. /**
  5834. * Indicates if a texture should be handled like a texture array.
  5835. *
  5836. * @type {boolean}
  5837. * @readonly
  5838. * @default false
  5839. */
  5840. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5841. /**
  5842. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5843. * (only relevant for render target textures).
  5844. *
  5845. * @type {number}
  5846. * @readonly
  5847. * @default 0
  5848. */
  5849. this.pmremVersion = 0;
  5850. }
  5851. /**
  5852. * The width of the texture in pixels.
  5853. */
  5854. get width() {
  5855. return this.source.getSize( _tempVec3 ).x;
  5856. }
  5857. /**
  5858. * The height of the texture in pixels.
  5859. */
  5860. get height() {
  5861. return this.source.getSize( _tempVec3 ).y;
  5862. }
  5863. /**
  5864. * The depth of the texture in pixels.
  5865. */
  5866. get depth() {
  5867. return this.source.getSize( _tempVec3 ).z;
  5868. }
  5869. /**
  5870. * The image object holding the texture data.
  5871. *
  5872. * @type {?Object}
  5873. */
  5874. get image() {
  5875. return this.source.data;
  5876. }
  5877. set image( value = null ) {
  5878. this.source.data = value;
  5879. }
  5880. /**
  5881. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5882. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5883. */
  5884. updateMatrix() {
  5885. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5886. }
  5887. /**
  5888. * Adds a range of data in the data texture to be updated on the GPU.
  5889. *
  5890. * @param {number} start - Position at which to start update.
  5891. * @param {number} count - The number of components to update.
  5892. */
  5893. addUpdateRange( start, count ) {
  5894. this.updateRanges.push( { start, count } );
  5895. }
  5896. /**
  5897. * Clears the update ranges.
  5898. */
  5899. clearUpdateRanges() {
  5900. this.updateRanges.length = 0;
  5901. }
  5902. /**
  5903. * Returns a new texture with copied values from this instance.
  5904. *
  5905. * @return {Texture} A clone of this instance.
  5906. */
  5907. clone() {
  5908. return new this.constructor().copy( this );
  5909. }
  5910. /**
  5911. * Copies the values of the given texture to this instance.
  5912. *
  5913. * @param {Texture} source - The texture to copy.
  5914. * @return {Texture} A reference to this instance.
  5915. */
  5916. copy( source ) {
  5917. this.name = source.name;
  5918. this.source = source.source;
  5919. this.mipmaps = source.mipmaps.slice( 0 );
  5920. this.mapping = source.mapping;
  5921. this.channel = source.channel;
  5922. this.wrapS = source.wrapS;
  5923. this.wrapT = source.wrapT;
  5924. this.magFilter = source.magFilter;
  5925. this.minFilter = source.minFilter;
  5926. this.anisotropy = source.anisotropy;
  5927. this.format = source.format;
  5928. this.internalFormat = source.internalFormat;
  5929. this.type = source.type;
  5930. this.offset.copy( source.offset );
  5931. this.repeat.copy( source.repeat );
  5932. this.center.copy( source.center );
  5933. this.rotation = source.rotation;
  5934. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5935. this.matrix.copy( source.matrix );
  5936. this.generateMipmaps = source.generateMipmaps;
  5937. this.premultiplyAlpha = source.premultiplyAlpha;
  5938. this.flipY = source.flipY;
  5939. this.unpackAlignment = source.unpackAlignment;
  5940. this.colorSpace = source.colorSpace;
  5941. this.renderTarget = source.renderTarget;
  5942. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5943. this.isArrayTexture = source.isArrayTexture;
  5944. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5945. this.needsUpdate = true;
  5946. return this;
  5947. }
  5948. /**
  5949. * Sets this texture's properties based on `values`.
  5950. * @param {Object} values - A container with texture parameters.
  5951. */
  5952. setValues( values ) {
  5953. for ( const key in values ) {
  5954. const newValue = values[ key ];
  5955. if ( newValue === undefined ) {
  5956. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5957. continue;
  5958. }
  5959. const currentValue = this[ key ];
  5960. if ( currentValue === undefined ) {
  5961. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  5962. continue;
  5963. }
  5964. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5965. currentValue.copy( newValue );
  5966. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5967. currentValue.copy( newValue );
  5968. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5969. currentValue.copy( newValue );
  5970. } else {
  5971. this[ key ] = newValue;
  5972. }
  5973. }
  5974. }
  5975. /**
  5976. * Serializes the texture into JSON.
  5977. *
  5978. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5979. * @return {Object} A JSON object representing the serialized texture.
  5980. * @see {@link ObjectLoader#parse}
  5981. */
  5982. toJSON( meta ) {
  5983. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5984. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5985. return meta.textures[ this.uuid ];
  5986. }
  5987. const output = {
  5988. metadata: {
  5989. version: 4.7,
  5990. type: 'Texture',
  5991. generator: 'Texture.toJSON'
  5992. },
  5993. uuid: this.uuid,
  5994. name: this.name,
  5995. image: this.source.toJSON( meta ).uuid,
  5996. mapping: this.mapping,
  5997. channel: this.channel,
  5998. repeat: [ this.repeat.x, this.repeat.y ],
  5999. offset: [ this.offset.x, this.offset.y ],
  6000. center: [ this.center.x, this.center.y ],
  6001. rotation: this.rotation,
  6002. wrap: [ this.wrapS, this.wrapT ],
  6003. format: this.format,
  6004. internalFormat: this.internalFormat,
  6005. type: this.type,
  6006. colorSpace: this.colorSpace,
  6007. minFilter: this.minFilter,
  6008. magFilter: this.magFilter,
  6009. anisotropy: this.anisotropy,
  6010. flipY: this.flipY,
  6011. generateMipmaps: this.generateMipmaps,
  6012. premultiplyAlpha: this.premultiplyAlpha,
  6013. unpackAlignment: this.unpackAlignment
  6014. };
  6015. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  6016. if ( ! isRootObject ) {
  6017. meta.textures[ this.uuid ] = output;
  6018. }
  6019. return output;
  6020. }
  6021. /**
  6022. * Frees the GPU-related resources allocated by this instance. Call this
  6023. * method whenever this instance is no longer used in your app.
  6024. *
  6025. * @fires Texture#dispose
  6026. */
  6027. dispose() {
  6028. /**
  6029. * Fires when the texture has been disposed of.
  6030. *
  6031. * @event Texture#dispose
  6032. * @type {Object}
  6033. */
  6034. this.dispatchEvent( { type: 'dispose' } );
  6035. }
  6036. /**
  6037. * Transforms the given uv vector with the textures uv transformation matrix.
  6038. *
  6039. * @param {Vector2} uv - The uv vector.
  6040. * @return {Vector2} The transformed uv vector.
  6041. */
  6042. transformUv( uv ) {
  6043. if ( this.mapping !== UVMapping ) return uv;
  6044. uv.applyMatrix3( this.matrix );
  6045. if ( uv.x < 0 || uv.x > 1 ) {
  6046. switch ( this.wrapS ) {
  6047. case RepeatWrapping:
  6048. uv.x = uv.x - Math.floor( uv.x );
  6049. break;
  6050. case ClampToEdgeWrapping:
  6051. uv.x = uv.x < 0 ? 0 : 1;
  6052. break;
  6053. case MirroredRepeatWrapping:
  6054. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6055. uv.x = Math.ceil( uv.x ) - uv.x;
  6056. } else {
  6057. uv.x = uv.x - Math.floor( uv.x );
  6058. }
  6059. break;
  6060. }
  6061. }
  6062. if ( uv.y < 0 || uv.y > 1 ) {
  6063. switch ( this.wrapT ) {
  6064. case RepeatWrapping:
  6065. uv.y = uv.y - Math.floor( uv.y );
  6066. break;
  6067. case ClampToEdgeWrapping:
  6068. uv.y = uv.y < 0 ? 0 : 1;
  6069. break;
  6070. case MirroredRepeatWrapping:
  6071. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6072. uv.y = Math.ceil( uv.y ) - uv.y;
  6073. } else {
  6074. uv.y = uv.y - Math.floor( uv.y );
  6075. }
  6076. break;
  6077. }
  6078. }
  6079. if ( this.flipY ) {
  6080. uv.y = 1 - uv.y;
  6081. }
  6082. return uv;
  6083. }
  6084. /**
  6085. * Setting this property to `true` indicates the engine the texture
  6086. * must be updated in the next render. This triggers a texture upload
  6087. * to the GPU and ensures correct texture parameter configuration.
  6088. *
  6089. * @type {boolean}
  6090. * @default false
  6091. * @param {boolean} value
  6092. */
  6093. set needsUpdate( value ) {
  6094. if ( value === true ) {
  6095. this.version ++;
  6096. this.source.needsUpdate = true;
  6097. }
  6098. }
  6099. /**
  6100. * Setting this property to `true` indicates the engine the PMREM
  6101. * must be regenerated.
  6102. *
  6103. * @type {boolean}
  6104. * @default false
  6105. * @param {boolean} value
  6106. */
  6107. set needsPMREMUpdate( value ) {
  6108. if ( value === true ) {
  6109. this.pmremVersion ++;
  6110. }
  6111. }
  6112. }
  6113. /**
  6114. * The default image for all textures.
  6115. *
  6116. * @static
  6117. * @type {?Image}
  6118. * @default null
  6119. */
  6120. Texture.DEFAULT_IMAGE = null;
  6121. /**
  6122. * The default mapping for all textures.
  6123. *
  6124. * @static
  6125. * @type {number}
  6126. * @default UVMapping
  6127. */
  6128. Texture.DEFAULT_MAPPING = UVMapping;
  6129. /**
  6130. * The default anisotropy value for all textures.
  6131. *
  6132. * @static
  6133. * @type {number}
  6134. * @default 1
  6135. */
  6136. Texture.DEFAULT_ANISOTROPY = 1;
  6137. /**
  6138. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  6139. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  6140. *
  6141. * - A point in 4D space.
  6142. * - A direction and length in 4D space. In three.js the length will
  6143. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  6144. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  6145. * - Any arbitrary ordered quadruplet of numbers.
  6146. *
  6147. * There are other things a 4D vector can be used to represent, however these
  6148. * are the most common uses in *three.js*.
  6149. *
  6150. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6151. * the corresponding order.
  6152. * ```js
  6153. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6154. *
  6155. * //no arguments; will be initialised to (0, 0, 0, 1)
  6156. * const b = new THREE.Vector4( );
  6157. *
  6158. * const d = a.dot( b );
  6159. * ```
  6160. */
  6161. class Vector4 {
  6162. /**
  6163. * Constructs a new 4D vector.
  6164. *
  6165. * @param {number} [x=0] - The x value of this vector.
  6166. * @param {number} [y=0] - The y value of this vector.
  6167. * @param {number} [z=0] - The z value of this vector.
  6168. * @param {number} [w=1] - The w value of this vector.
  6169. */
  6170. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6171. /**
  6172. * This flag can be used for type testing.
  6173. *
  6174. * @type {boolean}
  6175. * @readonly
  6176. * @default true
  6177. */
  6178. Vector4.prototype.isVector4 = true;
  6179. /**
  6180. * The x value of this vector.
  6181. *
  6182. * @type {number}
  6183. */
  6184. this.x = x;
  6185. /**
  6186. * The y value of this vector.
  6187. *
  6188. * @type {number}
  6189. */
  6190. this.y = y;
  6191. /**
  6192. * The z value of this vector.
  6193. *
  6194. * @type {number}
  6195. */
  6196. this.z = z;
  6197. /**
  6198. * The w value of this vector.
  6199. *
  6200. * @type {number}
  6201. */
  6202. this.w = w;
  6203. }
  6204. /**
  6205. * Alias for {@link Vector4#z}.
  6206. *
  6207. * @type {number}
  6208. */
  6209. get width() {
  6210. return this.z;
  6211. }
  6212. set width( value ) {
  6213. this.z = value;
  6214. }
  6215. /**
  6216. * Alias for {@link Vector4#w}.
  6217. *
  6218. * @type {number}
  6219. */
  6220. get height() {
  6221. return this.w;
  6222. }
  6223. set height( value ) {
  6224. this.w = value;
  6225. }
  6226. /**
  6227. * Sets the vector components.
  6228. *
  6229. * @param {number} x - The value of the x component.
  6230. * @param {number} y - The value of the y component.
  6231. * @param {number} z - The value of the z component.
  6232. * @param {number} w - The value of the w component.
  6233. * @return {Vector4} A reference to this vector.
  6234. */
  6235. set( x, y, z, w ) {
  6236. this.x = x;
  6237. this.y = y;
  6238. this.z = z;
  6239. this.w = w;
  6240. return this;
  6241. }
  6242. /**
  6243. * Sets the vector components to the same value.
  6244. *
  6245. * @param {number} scalar - The value to set for all vector components.
  6246. * @return {Vector4} A reference to this vector.
  6247. */
  6248. setScalar( scalar ) {
  6249. this.x = scalar;
  6250. this.y = scalar;
  6251. this.z = scalar;
  6252. this.w = scalar;
  6253. return this;
  6254. }
  6255. /**
  6256. * Sets the vector's x component to the given value
  6257. *
  6258. * @param {number} x - The value to set.
  6259. * @return {Vector4} A reference to this vector.
  6260. */
  6261. setX( x ) {
  6262. this.x = x;
  6263. return this;
  6264. }
  6265. /**
  6266. * Sets the vector's y component to the given value
  6267. *
  6268. * @param {number} y - The value to set.
  6269. * @return {Vector4} A reference to this vector.
  6270. */
  6271. setY( y ) {
  6272. this.y = y;
  6273. return this;
  6274. }
  6275. /**
  6276. * Sets the vector's z component to the given value
  6277. *
  6278. * @param {number} z - The value to set.
  6279. * @return {Vector4} A reference to this vector.
  6280. */
  6281. setZ( z ) {
  6282. this.z = z;
  6283. return this;
  6284. }
  6285. /**
  6286. * Sets the vector's w component to the given value
  6287. *
  6288. * @param {number} w - The value to set.
  6289. * @return {Vector4} A reference to this vector.
  6290. */
  6291. setW( w ) {
  6292. this.w = w;
  6293. return this;
  6294. }
  6295. /**
  6296. * Allows to set a vector component with an index.
  6297. *
  6298. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6299. * `2` equals to z, `3` equals to w.
  6300. * @param {number} value - The value to set.
  6301. * @return {Vector4} A reference to this vector.
  6302. */
  6303. setComponent( index, value ) {
  6304. switch ( index ) {
  6305. case 0: this.x = value; break;
  6306. case 1: this.y = value; break;
  6307. case 2: this.z = value; break;
  6308. case 3: this.w = value; break;
  6309. default: throw new Error( 'index is out of range: ' + index );
  6310. }
  6311. return this;
  6312. }
  6313. /**
  6314. * Returns the value of the vector component which matches the given index.
  6315. *
  6316. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6317. * `2` equals to z, `3` equals to w.
  6318. * @return {number} A vector component value.
  6319. */
  6320. getComponent( index ) {
  6321. switch ( index ) {
  6322. case 0: return this.x;
  6323. case 1: return this.y;
  6324. case 2: return this.z;
  6325. case 3: return this.w;
  6326. default: throw new Error( 'index is out of range: ' + index );
  6327. }
  6328. }
  6329. /**
  6330. * Returns a new vector with copied values from this instance.
  6331. *
  6332. * @return {Vector4} A clone of this instance.
  6333. */
  6334. clone() {
  6335. return new this.constructor( this.x, this.y, this.z, this.w );
  6336. }
  6337. /**
  6338. * Copies the values of the given vector to this instance.
  6339. *
  6340. * @param {Vector3|Vector4} v - The vector to copy.
  6341. * @return {Vector4} A reference to this vector.
  6342. */
  6343. copy( v ) {
  6344. this.x = v.x;
  6345. this.y = v.y;
  6346. this.z = v.z;
  6347. this.w = ( v.w !== undefined ) ? v.w : 1;
  6348. return this;
  6349. }
  6350. /**
  6351. * Adds the given vector to this instance.
  6352. *
  6353. * @param {Vector4} v - The vector to add.
  6354. * @return {Vector4} A reference to this vector.
  6355. */
  6356. add( v ) {
  6357. this.x += v.x;
  6358. this.y += v.y;
  6359. this.z += v.z;
  6360. this.w += v.w;
  6361. return this;
  6362. }
  6363. /**
  6364. * Adds the given scalar value to all components of this instance.
  6365. *
  6366. * @param {number} s - The scalar to add.
  6367. * @return {Vector4} A reference to this vector.
  6368. */
  6369. addScalar( s ) {
  6370. this.x += s;
  6371. this.y += s;
  6372. this.z += s;
  6373. this.w += s;
  6374. return this;
  6375. }
  6376. /**
  6377. * Adds the given vectors and stores the result in this instance.
  6378. *
  6379. * @param {Vector4} a - The first vector.
  6380. * @param {Vector4} b - The second vector.
  6381. * @return {Vector4} A reference to this vector.
  6382. */
  6383. addVectors( a, b ) {
  6384. this.x = a.x + b.x;
  6385. this.y = a.y + b.y;
  6386. this.z = a.z + b.z;
  6387. this.w = a.w + b.w;
  6388. return this;
  6389. }
  6390. /**
  6391. * Adds the given vector scaled by the given factor to this instance.
  6392. *
  6393. * @param {Vector4} v - The vector.
  6394. * @param {number} s - The factor that scales `v`.
  6395. * @return {Vector4} A reference to this vector.
  6396. */
  6397. addScaledVector( v, s ) {
  6398. this.x += v.x * s;
  6399. this.y += v.y * s;
  6400. this.z += v.z * s;
  6401. this.w += v.w * s;
  6402. return this;
  6403. }
  6404. /**
  6405. * Subtracts the given vector from this instance.
  6406. *
  6407. * @param {Vector4} v - The vector to subtract.
  6408. * @return {Vector4} A reference to this vector.
  6409. */
  6410. sub( v ) {
  6411. this.x -= v.x;
  6412. this.y -= v.y;
  6413. this.z -= v.z;
  6414. this.w -= v.w;
  6415. return this;
  6416. }
  6417. /**
  6418. * Subtracts the given scalar value from all components of this instance.
  6419. *
  6420. * @param {number} s - The scalar to subtract.
  6421. * @return {Vector4} A reference to this vector.
  6422. */
  6423. subScalar( s ) {
  6424. this.x -= s;
  6425. this.y -= s;
  6426. this.z -= s;
  6427. this.w -= s;
  6428. return this;
  6429. }
  6430. /**
  6431. * Subtracts the given vectors and stores the result in this instance.
  6432. *
  6433. * @param {Vector4} a - The first vector.
  6434. * @param {Vector4} b - The second vector.
  6435. * @return {Vector4} A reference to this vector.
  6436. */
  6437. subVectors( a, b ) {
  6438. this.x = a.x - b.x;
  6439. this.y = a.y - b.y;
  6440. this.z = a.z - b.z;
  6441. this.w = a.w - b.w;
  6442. return this;
  6443. }
  6444. /**
  6445. * Multiplies the given vector with this instance.
  6446. *
  6447. * @param {Vector4} v - The vector to multiply.
  6448. * @return {Vector4} A reference to this vector.
  6449. */
  6450. multiply( v ) {
  6451. this.x *= v.x;
  6452. this.y *= v.y;
  6453. this.z *= v.z;
  6454. this.w *= v.w;
  6455. return this;
  6456. }
  6457. /**
  6458. * Multiplies the given scalar value with all components of this instance.
  6459. *
  6460. * @param {number} scalar - The scalar to multiply.
  6461. * @return {Vector4} A reference to this vector.
  6462. */
  6463. multiplyScalar( scalar ) {
  6464. this.x *= scalar;
  6465. this.y *= scalar;
  6466. this.z *= scalar;
  6467. this.w *= scalar;
  6468. return this;
  6469. }
  6470. /**
  6471. * Multiplies this vector with the given 4x4 matrix.
  6472. *
  6473. * @param {Matrix4} m - The 4x4 matrix.
  6474. * @return {Vector4} A reference to this vector.
  6475. */
  6476. applyMatrix4( m ) {
  6477. const x = this.x, y = this.y, z = this.z, w = this.w;
  6478. const e = m.elements;
  6479. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6480. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6481. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6482. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6483. return this;
  6484. }
  6485. /**
  6486. * Divides this instance by the given vector.
  6487. *
  6488. * @param {Vector4} v - The vector to divide.
  6489. * @return {Vector4} A reference to this vector.
  6490. */
  6491. divide( v ) {
  6492. this.x /= v.x;
  6493. this.y /= v.y;
  6494. this.z /= v.z;
  6495. this.w /= v.w;
  6496. return this;
  6497. }
  6498. /**
  6499. * Divides this vector by the given scalar.
  6500. *
  6501. * @param {number} scalar - The scalar to divide.
  6502. * @return {Vector4} A reference to this vector.
  6503. */
  6504. divideScalar( scalar ) {
  6505. return this.multiplyScalar( 1 / scalar );
  6506. }
  6507. /**
  6508. * Sets the x, y and z components of this
  6509. * vector to the quaternion's axis and w to the angle.
  6510. *
  6511. * @param {Quaternion} q - The Quaternion to set.
  6512. * @return {Vector4} A reference to this vector.
  6513. */
  6514. setAxisAngleFromQuaternion( q ) {
  6515. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6516. // q is assumed to be normalized
  6517. this.w = 2 * Math.acos( q.w );
  6518. const s = Math.sqrt( 1 - q.w * q.w );
  6519. if ( s < 0.0001 ) {
  6520. this.x = 1;
  6521. this.y = 0;
  6522. this.z = 0;
  6523. } else {
  6524. this.x = q.x / s;
  6525. this.y = q.y / s;
  6526. this.z = q.z / s;
  6527. }
  6528. return this;
  6529. }
  6530. /**
  6531. * Sets the x, y and z components of this
  6532. * vector to the axis of rotation and w to the angle.
  6533. *
  6534. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6535. * @return {Vector4} A reference to this vector.
  6536. */
  6537. setAxisAngleFromRotationMatrix( m ) {
  6538. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6539. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6540. let angle, x, y, z; // variables for result
  6541. const epsilon = 0.01, // margin to allow for rounding errors
  6542. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6543. te = m.elements,
  6544. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6545. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6546. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6547. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6548. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6549. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6550. // singularity found
  6551. // first check for identity matrix which must have +1 for all terms
  6552. // in leading diagonal and zero in other terms
  6553. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6554. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6555. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6556. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6557. // this singularity is identity matrix so angle = 0
  6558. this.set( 1, 0, 0, 0 );
  6559. return this; // zero angle, arbitrary axis
  6560. }
  6561. // otherwise this singularity is angle = 180
  6562. angle = Math.PI;
  6563. const xx = ( m11 + 1 ) / 2;
  6564. const yy = ( m22 + 1 ) / 2;
  6565. const zz = ( m33 + 1 ) / 2;
  6566. const xy = ( m12 + m21 ) / 4;
  6567. const xz = ( m13 + m31 ) / 4;
  6568. const yz = ( m23 + m32 ) / 4;
  6569. if ( ( xx > yy ) && ( xx > zz ) ) {
  6570. // m11 is the largest diagonal term
  6571. if ( xx < epsilon ) {
  6572. x = 0;
  6573. y = 0.707106781;
  6574. z = 0.707106781;
  6575. } else {
  6576. x = Math.sqrt( xx );
  6577. y = xy / x;
  6578. z = xz / x;
  6579. }
  6580. } else if ( yy > zz ) {
  6581. // m22 is the largest diagonal term
  6582. if ( yy < epsilon ) {
  6583. x = 0.707106781;
  6584. y = 0;
  6585. z = 0.707106781;
  6586. } else {
  6587. y = Math.sqrt( yy );
  6588. x = xy / y;
  6589. z = yz / y;
  6590. }
  6591. } else {
  6592. // m33 is the largest diagonal term so base result on this
  6593. if ( zz < epsilon ) {
  6594. x = 0.707106781;
  6595. y = 0.707106781;
  6596. z = 0;
  6597. } else {
  6598. z = Math.sqrt( zz );
  6599. x = xz / z;
  6600. y = yz / z;
  6601. }
  6602. }
  6603. this.set( x, y, z, angle );
  6604. return this; // return 180 deg rotation
  6605. }
  6606. // as we have reached here there are no singularities so we can handle normally
  6607. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6608. ( m13 - m31 ) * ( m13 - m31 ) +
  6609. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6610. if ( Math.abs( s ) < 0.001 ) s = 1;
  6611. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6612. // caught by singularity test above, but I've left it in just in case
  6613. this.x = ( m32 - m23 ) / s;
  6614. this.y = ( m13 - m31 ) / s;
  6615. this.z = ( m21 - m12 ) / s;
  6616. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6617. return this;
  6618. }
  6619. /**
  6620. * Sets the vector components to the position elements of the
  6621. * given transformation matrix.
  6622. *
  6623. * @param {Matrix4} m - The 4x4 matrix.
  6624. * @return {Vector4} A reference to this vector.
  6625. */
  6626. setFromMatrixPosition( m ) {
  6627. const e = m.elements;
  6628. this.x = e[ 12 ];
  6629. this.y = e[ 13 ];
  6630. this.z = e[ 14 ];
  6631. this.w = e[ 15 ];
  6632. return this;
  6633. }
  6634. /**
  6635. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6636. * value, replace that value with the corresponding min value.
  6637. *
  6638. * @param {Vector4} v - The vector.
  6639. * @return {Vector4} A reference to this vector.
  6640. */
  6641. min( v ) {
  6642. this.x = Math.min( this.x, v.x );
  6643. this.y = Math.min( this.y, v.y );
  6644. this.z = Math.min( this.z, v.z );
  6645. this.w = Math.min( this.w, v.w );
  6646. return this;
  6647. }
  6648. /**
  6649. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6650. * value, replace that value with the corresponding max value.
  6651. *
  6652. * @param {Vector4} v - The vector.
  6653. * @return {Vector4} A reference to this vector.
  6654. */
  6655. max( v ) {
  6656. this.x = Math.max( this.x, v.x );
  6657. this.y = Math.max( this.y, v.y );
  6658. this.z = Math.max( this.z, v.z );
  6659. this.w = Math.max( this.w, v.w );
  6660. return this;
  6661. }
  6662. /**
  6663. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6664. * value, it is replaced by the corresponding value.
  6665. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6666. * it is replaced by the corresponding value.
  6667. *
  6668. * @param {Vector4} min - The minimum x, y and z values.
  6669. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6670. * @return {Vector4} A reference to this vector.
  6671. */
  6672. clamp( min, max ) {
  6673. // assumes min < max, componentwise
  6674. this.x = clamp( this.x, min.x, max.x );
  6675. this.y = clamp( this.y, min.y, max.y );
  6676. this.z = clamp( this.z, min.z, max.z );
  6677. this.w = clamp( this.w, min.w, max.w );
  6678. return this;
  6679. }
  6680. /**
  6681. * If this vector's x, y, z or w values are greater than the max value, they are
  6682. * replaced by the max value.
  6683. * If this vector's x, y, z or w values are less than the min value, they are
  6684. * replaced by the min value.
  6685. *
  6686. * @param {number} minVal - The minimum value the components will be clamped to.
  6687. * @param {number} maxVal - The maximum value the components will be clamped to.
  6688. * @return {Vector4} A reference to this vector.
  6689. */
  6690. clampScalar( minVal, maxVal ) {
  6691. this.x = clamp( this.x, minVal, maxVal );
  6692. this.y = clamp( this.y, minVal, maxVal );
  6693. this.z = clamp( this.z, minVal, maxVal );
  6694. this.w = clamp( this.w, minVal, maxVal );
  6695. return this;
  6696. }
  6697. /**
  6698. * If this vector's length is greater than the max value, it is replaced by
  6699. * the max value.
  6700. * If this vector's length is less than the min value, it is replaced by the
  6701. * min value.
  6702. *
  6703. * @param {number} min - The minimum value the vector length will be clamped to.
  6704. * @param {number} max - The maximum value the vector length will be clamped to.
  6705. * @return {Vector4} A reference to this vector.
  6706. */
  6707. clampLength( min, max ) {
  6708. const length = this.length();
  6709. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6710. }
  6711. /**
  6712. * The components of this vector are rounded down to the nearest integer value.
  6713. *
  6714. * @return {Vector4} A reference to this vector.
  6715. */
  6716. floor() {
  6717. this.x = Math.floor( this.x );
  6718. this.y = Math.floor( this.y );
  6719. this.z = Math.floor( this.z );
  6720. this.w = Math.floor( this.w );
  6721. return this;
  6722. }
  6723. /**
  6724. * The components of this vector are rounded up to the nearest integer value.
  6725. *
  6726. * @return {Vector4} A reference to this vector.
  6727. */
  6728. ceil() {
  6729. this.x = Math.ceil( this.x );
  6730. this.y = Math.ceil( this.y );
  6731. this.z = Math.ceil( this.z );
  6732. this.w = Math.ceil( this.w );
  6733. return this;
  6734. }
  6735. /**
  6736. * The components of this vector are rounded to the nearest integer value
  6737. *
  6738. * @return {Vector4} A reference to this vector.
  6739. */
  6740. round() {
  6741. this.x = Math.round( this.x );
  6742. this.y = Math.round( this.y );
  6743. this.z = Math.round( this.z );
  6744. this.w = Math.round( this.w );
  6745. return this;
  6746. }
  6747. /**
  6748. * The components of this vector are rounded towards zero (up if negative,
  6749. * down if positive) to an integer value.
  6750. *
  6751. * @return {Vector4} A reference to this vector.
  6752. */
  6753. roundToZero() {
  6754. this.x = Math.trunc( this.x );
  6755. this.y = Math.trunc( this.y );
  6756. this.z = Math.trunc( this.z );
  6757. this.w = Math.trunc( this.w );
  6758. return this;
  6759. }
  6760. /**
  6761. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6762. *
  6763. * @return {Vector4} A reference to this vector.
  6764. */
  6765. negate() {
  6766. this.x = - this.x;
  6767. this.y = - this.y;
  6768. this.z = - this.z;
  6769. this.w = - this.w;
  6770. return this;
  6771. }
  6772. /**
  6773. * Calculates the dot product of the given vector with this instance.
  6774. *
  6775. * @param {Vector4} v - The vector to compute the dot product with.
  6776. * @return {number} The result of the dot product.
  6777. */
  6778. dot( v ) {
  6779. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6780. }
  6781. /**
  6782. * Computes the square of the Euclidean length (straight-line length) from
  6783. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6784. * compare the length squared instead as it is slightly more efficient to calculate.
  6785. *
  6786. * @return {number} The square length of this vector.
  6787. */
  6788. lengthSq() {
  6789. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6790. }
  6791. /**
  6792. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6793. *
  6794. * @return {number} The length of this vector.
  6795. */
  6796. length() {
  6797. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6798. }
  6799. /**
  6800. * Computes the Manhattan length of this vector.
  6801. *
  6802. * @return {number} The length of this vector.
  6803. */
  6804. manhattanLength() {
  6805. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6806. }
  6807. /**
  6808. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6809. * with the same direction as this one, but with a vector length of `1`.
  6810. *
  6811. * @return {Vector4} A reference to this vector.
  6812. */
  6813. normalize() {
  6814. return this.divideScalar( this.length() || 1 );
  6815. }
  6816. /**
  6817. * Sets this vector to a vector with the same direction as this one, but
  6818. * with the specified length.
  6819. *
  6820. * @param {number} length - The new length of this vector.
  6821. * @return {Vector4} A reference to this vector.
  6822. */
  6823. setLength( length ) {
  6824. return this.normalize().multiplyScalar( length );
  6825. }
  6826. /**
  6827. * Linearly interpolates between the given vector and this instance, where
  6828. * alpha is the percent distance along the line - alpha = 0 will be this
  6829. * vector, and alpha = 1 will be the given one.
  6830. *
  6831. * @param {Vector4} v - The vector to interpolate towards.
  6832. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6833. * @return {Vector4} A reference to this vector.
  6834. */
  6835. lerp( v, alpha ) {
  6836. this.x += ( v.x - this.x ) * alpha;
  6837. this.y += ( v.y - this.y ) * alpha;
  6838. this.z += ( v.z - this.z ) * alpha;
  6839. this.w += ( v.w - this.w ) * alpha;
  6840. return this;
  6841. }
  6842. /**
  6843. * Linearly interpolates between the given vectors, where alpha is the percent
  6844. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6845. * be the second one. The result is stored in this instance.
  6846. *
  6847. * @param {Vector4} v1 - The first vector.
  6848. * @param {Vector4} v2 - The second vector.
  6849. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6850. * @return {Vector4} A reference to this vector.
  6851. */
  6852. lerpVectors( v1, v2, alpha ) {
  6853. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6854. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6855. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6856. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6857. return this;
  6858. }
  6859. /**
  6860. * Returns `true` if this vector is equal with the given one.
  6861. *
  6862. * @param {Vector4} v - The vector to test for equality.
  6863. * @return {boolean} Whether this vector is equal with the given one.
  6864. */
  6865. equals( v ) {
  6866. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6867. }
  6868. /**
  6869. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6870. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6871. *
  6872. * @param {Array<number>} array - An array holding the vector component values.
  6873. * @param {number} [offset=0] - The offset into the array.
  6874. * @return {Vector4} A reference to this vector.
  6875. */
  6876. fromArray( array, offset = 0 ) {
  6877. this.x = array[ offset ];
  6878. this.y = array[ offset + 1 ];
  6879. this.z = array[ offset + 2 ];
  6880. this.w = array[ offset + 3 ];
  6881. return this;
  6882. }
  6883. /**
  6884. * Writes the components of this vector to the given array. If no array is provided,
  6885. * the method returns a new instance.
  6886. *
  6887. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6888. * @param {number} [offset=0] - Index of the first element in the array.
  6889. * @return {Array<number>} The vector components.
  6890. */
  6891. toArray( array = [], offset = 0 ) {
  6892. array[ offset ] = this.x;
  6893. array[ offset + 1 ] = this.y;
  6894. array[ offset + 2 ] = this.z;
  6895. array[ offset + 3 ] = this.w;
  6896. return array;
  6897. }
  6898. /**
  6899. * Sets the components of this vector from the given buffer attribute.
  6900. *
  6901. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6902. * @param {number} index - The index into the attribute.
  6903. * @return {Vector4} A reference to this vector.
  6904. */
  6905. fromBufferAttribute( attribute, index ) {
  6906. this.x = attribute.getX( index );
  6907. this.y = attribute.getY( index );
  6908. this.z = attribute.getZ( index );
  6909. this.w = attribute.getW( index );
  6910. return this;
  6911. }
  6912. /**
  6913. * Sets each component of this vector to a pseudo-random value between `0` and
  6914. * `1`, excluding `1`.
  6915. *
  6916. * @return {Vector4} A reference to this vector.
  6917. */
  6918. random() {
  6919. this.x = Math.random();
  6920. this.y = Math.random();
  6921. this.z = Math.random();
  6922. this.w = Math.random();
  6923. return this;
  6924. }
  6925. *[ Symbol.iterator ]() {
  6926. yield this.x;
  6927. yield this.y;
  6928. yield this.z;
  6929. yield this.w;
  6930. }
  6931. }
  6932. /**
  6933. * A render target is a buffer where the video card draws pixels for a scene
  6934. * that is being rendered in the background. It is used in different effects,
  6935. * such as applying postprocessing to a rendered image before displaying it
  6936. * on the screen.
  6937. *
  6938. * @augments EventDispatcher
  6939. */
  6940. class RenderTarget extends EventDispatcher {
  6941. /**
  6942. * Render target options.
  6943. *
  6944. * @typedef {Object} RenderTarget~Options
  6945. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6946. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6947. * @property {number} [minFilter=LinearFilter] - The min filter.
  6948. * @property {number} [format=RGBAFormat] - The texture format.
  6949. * @property {number} [type=UnsignedByteType] - The texture type.
  6950. * @property {?string} [internalFormat=null] - The texture's internal format.
  6951. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6952. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6953. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6954. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6955. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6956. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6957. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6958. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6959. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6960. * @property {number} [samples=0] - The MSAA samples count.
  6961. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6962. * @property {number} [depth=1] - The texture depth.
  6963. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6964. */
  6965. /**
  6966. * Constructs a new render target.
  6967. *
  6968. * @param {number} [width=1] - The width of the render target.
  6969. * @param {number} [height=1] - The height of the render target.
  6970. * @param {RenderTarget~Options} [options] - The configuration object.
  6971. */
  6972. constructor( width = 1, height = 1, options = {} ) {
  6973. super();
  6974. options = Object.assign( {
  6975. generateMipmaps: false,
  6976. internalFormat: null,
  6977. minFilter: LinearFilter,
  6978. depthBuffer: true,
  6979. stencilBuffer: false,
  6980. resolveDepthBuffer: true,
  6981. resolveStencilBuffer: true,
  6982. depthTexture: null,
  6983. samples: 0,
  6984. count: 1,
  6985. depth: 1,
  6986. multiview: false
  6987. }, options );
  6988. /**
  6989. * This flag can be used for type testing.
  6990. *
  6991. * @type {boolean}
  6992. * @readonly
  6993. * @default true
  6994. */
  6995. this.isRenderTarget = true;
  6996. /**
  6997. * The width of the render target.
  6998. *
  6999. * @type {number}
  7000. * @default 1
  7001. */
  7002. this.width = width;
  7003. /**
  7004. * The height of the render target.
  7005. *
  7006. * @type {number}
  7007. * @default 1
  7008. */
  7009. this.height = height;
  7010. /**
  7011. * The depth of the render target.
  7012. *
  7013. * @type {number}
  7014. * @default 1
  7015. */
  7016. this.depth = options.depth;
  7017. /**
  7018. * A rectangular area inside the render target's viewport. Fragments that are
  7019. * outside the area will be discarded.
  7020. *
  7021. * @type {Vector4}
  7022. * @default (0,0,width,height)
  7023. */
  7024. this.scissor = new Vector4( 0, 0, width, height );
  7025. /**
  7026. * Indicates whether the scissor test should be enabled when rendering into
  7027. * this render target or not.
  7028. *
  7029. * @type {boolean}
  7030. * @default false
  7031. */
  7032. this.scissorTest = false;
  7033. /**
  7034. * A rectangular area representing the render target's viewport.
  7035. *
  7036. * @type {Vector4}
  7037. * @default (0,0,width,height)
  7038. */
  7039. this.viewport = new Vector4( 0, 0, width, height );
  7040. const image = { width: width, height: height, depth: options.depth };
  7041. const texture = new Texture( image );
  7042. /**
  7043. * An array of textures. Each color attachment is represented as a separate texture.
  7044. * Has at least a single entry for the default color attachment.
  7045. *
  7046. * @type {Array<Texture>}
  7047. */
  7048. this.textures = [];
  7049. const count = options.count;
  7050. for ( let i = 0; i < count; i ++ ) {
  7051. this.textures[ i ] = texture.clone();
  7052. this.textures[ i ].isRenderTargetTexture = true;
  7053. this.textures[ i ].renderTarget = this;
  7054. }
  7055. this._setTextureOptions( options );
  7056. /**
  7057. * Whether to allocate a depth buffer or not.
  7058. *
  7059. * @type {boolean}
  7060. * @default true
  7061. */
  7062. this.depthBuffer = options.depthBuffer;
  7063. /**
  7064. * Whether to allocate a stencil buffer or not.
  7065. *
  7066. * @type {boolean}
  7067. * @default false
  7068. */
  7069. this.stencilBuffer = options.stencilBuffer;
  7070. /**
  7071. * Whether to resolve the depth buffer or not.
  7072. *
  7073. * @type {boolean}
  7074. * @default true
  7075. */
  7076. this.resolveDepthBuffer = options.resolveDepthBuffer;
  7077. /**
  7078. * Whether to resolve the stencil buffer or not.
  7079. *
  7080. * @type {boolean}
  7081. * @default true
  7082. */
  7083. this.resolveStencilBuffer = options.resolveStencilBuffer;
  7084. this._depthTexture = null;
  7085. this.depthTexture = options.depthTexture;
  7086. /**
  7087. * The number of MSAA samples.
  7088. *
  7089. * A value of `0` disables MSAA.
  7090. *
  7091. * @type {number}
  7092. * @default 0
  7093. */
  7094. this.samples = options.samples;
  7095. /**
  7096. * Whether to this target is used in multiview rendering.
  7097. *
  7098. * @type {boolean}
  7099. * @default false
  7100. */
  7101. this.multiview = options.multiview;
  7102. }
  7103. _setTextureOptions( options = {} ) {
  7104. const values = {
  7105. minFilter: LinearFilter,
  7106. generateMipmaps: false,
  7107. flipY: false,
  7108. internalFormat: null
  7109. };
  7110. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  7111. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  7112. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  7113. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  7114. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  7115. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  7116. if ( options.format !== undefined ) values.format = options.format;
  7117. if ( options.type !== undefined ) values.type = options.type;
  7118. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  7119. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  7120. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  7121. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  7122. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  7123. for ( let i = 0; i < this.textures.length; i ++ ) {
  7124. const texture = this.textures[ i ];
  7125. texture.setValues( values );
  7126. }
  7127. }
  7128. /**
  7129. * The texture representing the default color attachment.
  7130. *
  7131. * @type {Texture}
  7132. */
  7133. get texture() {
  7134. return this.textures[ 0 ];
  7135. }
  7136. set texture( value ) {
  7137. this.textures[ 0 ] = value;
  7138. }
  7139. set depthTexture( current ) {
  7140. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  7141. if ( current !== null ) current.renderTarget = this;
  7142. this._depthTexture = current;
  7143. }
  7144. /**
  7145. * Instead of saving the depth in a renderbuffer, a texture
  7146. * can be used instead which is useful for further processing
  7147. * e.g. in context of post-processing.
  7148. *
  7149. * @type {?DepthTexture}
  7150. * @default null
  7151. */
  7152. get depthTexture() {
  7153. return this._depthTexture;
  7154. }
  7155. /**
  7156. * Sets the size of this render target.
  7157. *
  7158. * @param {number} width - The width.
  7159. * @param {number} height - The height.
  7160. * @param {number} [depth=1] - The depth.
  7161. */
  7162. setSize( width, height, depth = 1 ) {
  7163. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7164. this.width = width;
  7165. this.height = height;
  7166. this.depth = depth;
  7167. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7168. this.textures[ i ].image.width = width;
  7169. this.textures[ i ].image.height = height;
  7170. this.textures[ i ].image.depth = depth;
  7171. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7172. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7173. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7174. // both are evaluated on each call?
  7175. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7176. }
  7177. }
  7178. this.dispose();
  7179. }
  7180. this.viewport.set( 0, 0, width, height );
  7181. this.scissor.set( 0, 0, width, height );
  7182. }
  7183. /**
  7184. * Returns a new render target with copied values from this instance.
  7185. *
  7186. * @return {RenderTarget} A clone of this instance.
  7187. */
  7188. clone() {
  7189. return new this.constructor().copy( this );
  7190. }
  7191. /**
  7192. * Copies the settings of the given render target. This is a structural copy so
  7193. * no resources are shared between render targets after the copy. That includes
  7194. * all MRT textures and the depth texture.
  7195. *
  7196. * @param {RenderTarget} source - The render target to copy.
  7197. * @return {RenderTarget} A reference to this instance.
  7198. */
  7199. copy( source ) {
  7200. this.width = source.width;
  7201. this.height = source.height;
  7202. this.depth = source.depth;
  7203. this.scissor.copy( source.scissor );
  7204. this.scissorTest = source.scissorTest;
  7205. this.viewport.copy( source.viewport );
  7206. this.textures.length = 0;
  7207. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7208. this.textures[ i ] = source.textures[ i ].clone();
  7209. this.textures[ i ].isRenderTargetTexture = true;
  7210. this.textures[ i ].renderTarget = this;
  7211. // ensure image object is not shared, see #20328
  7212. const image = Object.assign( {}, source.textures[ i ].image );
  7213. this.textures[ i ].source = new Source( image );
  7214. }
  7215. this.depthBuffer = source.depthBuffer;
  7216. this.stencilBuffer = source.stencilBuffer;
  7217. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7218. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7219. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7220. this.samples = source.samples;
  7221. return this;
  7222. }
  7223. /**
  7224. * Frees the GPU-related resources allocated by this instance. Call this
  7225. * method whenever this instance is no longer used in your app.
  7226. *
  7227. * @fires RenderTarget#dispose
  7228. */
  7229. dispose() {
  7230. this.dispatchEvent( { type: 'dispose' } );
  7231. }
  7232. }
  7233. /**
  7234. * A render target used in context of {@link WebGLRenderer}.
  7235. *
  7236. * @augments RenderTarget
  7237. */
  7238. class WebGLRenderTarget extends RenderTarget {
  7239. /**
  7240. * Constructs a new 3D render target.
  7241. *
  7242. * @param {number} [width=1] - The width of the render target.
  7243. * @param {number} [height=1] - The height of the render target.
  7244. * @param {RenderTarget~Options} [options] - The configuration object.
  7245. */
  7246. constructor( width = 1, height = 1, options = {} ) {
  7247. super( width, height, options );
  7248. /**
  7249. * This flag can be used for type testing.
  7250. *
  7251. * @type {boolean}
  7252. * @readonly
  7253. * @default true
  7254. */
  7255. this.isWebGLRenderTarget = true;
  7256. }
  7257. }
  7258. /**
  7259. * Creates an array of textures directly from raw buffer data.
  7260. *
  7261. * @augments Texture
  7262. */
  7263. class DataArrayTexture extends Texture {
  7264. /**
  7265. * Constructs a new data array texture.
  7266. *
  7267. * @param {?TypedArray} [data=null] - The buffer data.
  7268. * @param {number} [width=1] - The width of the texture.
  7269. * @param {number} [height=1] - The height of the texture.
  7270. * @param {number} [depth=1] - The depth of the texture.
  7271. */
  7272. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7273. super( null );
  7274. /**
  7275. * This flag can be used for type testing.
  7276. *
  7277. * @type {boolean}
  7278. * @readonly
  7279. * @default true
  7280. */
  7281. this.isDataArrayTexture = true;
  7282. /**
  7283. * The image definition of a data texture.
  7284. *
  7285. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7286. */
  7287. this.image = { data, width, height, depth };
  7288. /**
  7289. * How the texture is sampled when a texel covers more than one pixel.
  7290. *
  7291. * Overwritten and set to `NearestFilter` by default.
  7292. *
  7293. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7294. * @default NearestFilter
  7295. */
  7296. this.magFilter = NearestFilter;
  7297. /**
  7298. * How the texture is sampled when a texel covers less than one pixel.
  7299. *
  7300. * Overwritten and set to `NearestFilter` by default.
  7301. *
  7302. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7303. * @default NearestFilter
  7304. */
  7305. this.minFilter = NearestFilter;
  7306. /**
  7307. * This defines how the texture is wrapped in the depth and corresponds to
  7308. * *W* in UVW mapping.
  7309. *
  7310. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7311. * @default ClampToEdgeWrapping
  7312. */
  7313. this.wrapR = ClampToEdgeWrapping;
  7314. /**
  7315. * Whether to generate mipmaps (if possible) for a texture.
  7316. *
  7317. * Overwritten and set to `false` by default.
  7318. *
  7319. * @type {boolean}
  7320. * @default false
  7321. */
  7322. this.generateMipmaps = false;
  7323. /**
  7324. * If set to `true`, the texture is flipped along the vertical axis when
  7325. * uploaded to the GPU.
  7326. *
  7327. * Overwritten and set to `false` by default.
  7328. *
  7329. * @type {boolean}
  7330. * @default false
  7331. */
  7332. this.flipY = false;
  7333. /**
  7334. * Specifies the alignment requirements for the start of each pixel row in memory.
  7335. *
  7336. * Overwritten and set to `1` by default.
  7337. *
  7338. * @type {boolean}
  7339. * @default 1
  7340. */
  7341. this.unpackAlignment = 1;
  7342. /**
  7343. * A set of all layers which need to be updated in the texture.
  7344. *
  7345. * @type {Set<number>}
  7346. */
  7347. this.layerUpdates = new Set();
  7348. }
  7349. /**
  7350. * Describes that a specific layer of the texture needs to be updated.
  7351. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7352. * entire data texture array is sent to the GPU. Marking specific
  7353. * layers will only transmit subsets of all mipmaps associated with a
  7354. * specific depth in the array which is often much more performant.
  7355. *
  7356. * @param {number} layerIndex - The layer index that should be updated.
  7357. */
  7358. addLayerUpdate( layerIndex ) {
  7359. this.layerUpdates.add( layerIndex );
  7360. }
  7361. /**
  7362. * Resets the layer updates registry.
  7363. */
  7364. clearLayerUpdates() {
  7365. this.layerUpdates.clear();
  7366. }
  7367. }
  7368. /**
  7369. * An array render target used in context of {@link WebGLRenderer}.
  7370. *
  7371. * @augments WebGLRenderTarget
  7372. */
  7373. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7374. /**
  7375. * Constructs a new array render target.
  7376. *
  7377. * @param {number} [width=1] - The width of the render target.
  7378. * @param {number} [height=1] - The height of the render target.
  7379. * @param {number} [depth=1] - The height of the render target.
  7380. * @param {RenderTarget~Options} [options] - The configuration object.
  7381. */
  7382. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7383. super( width, height, options );
  7384. /**
  7385. * This flag can be used for type testing.
  7386. *
  7387. * @type {boolean}
  7388. * @readonly
  7389. * @default true
  7390. */
  7391. this.isWebGLArrayRenderTarget = true;
  7392. this.depth = depth;
  7393. /**
  7394. * Overwritten with a different texture type.
  7395. *
  7396. * @type {DataArrayTexture}
  7397. */
  7398. this.texture = new DataArrayTexture( null, width, height, depth );
  7399. this._setTextureOptions( options );
  7400. this.texture.isRenderTargetTexture = true;
  7401. }
  7402. }
  7403. /**
  7404. * Creates a three-dimensional texture from raw data, with parameters to
  7405. * divide it into width, height, and depth.
  7406. *
  7407. * @augments Texture
  7408. */
  7409. class Data3DTexture extends Texture {
  7410. /**
  7411. * Constructs a new data array texture.
  7412. *
  7413. * @param {?TypedArray} [data=null] - The buffer data.
  7414. * @param {number} [width=1] - The width of the texture.
  7415. * @param {number} [height=1] - The height of the texture.
  7416. * @param {number} [depth=1] - The depth of the texture.
  7417. */
  7418. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7419. // We're going to add .setXXX() methods for setting properties later.
  7420. // Users can still set in Data3DTexture directly.
  7421. //
  7422. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7423. // texture.anisotropy = 16;
  7424. //
  7425. // See #14839
  7426. super( null );
  7427. /**
  7428. * This flag can be used for type testing.
  7429. *
  7430. * @type {boolean}
  7431. * @readonly
  7432. * @default true
  7433. */
  7434. this.isData3DTexture = true;
  7435. /**
  7436. * The image definition of a data texture.
  7437. *
  7438. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7439. */
  7440. this.image = { data, width, height, depth };
  7441. /**
  7442. * How the texture is sampled when a texel covers more than one pixel.
  7443. *
  7444. * Overwritten and set to `NearestFilter` by default.
  7445. *
  7446. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7447. * @default NearestFilter
  7448. */
  7449. this.magFilter = NearestFilter;
  7450. /**
  7451. * How the texture is sampled when a texel covers less than one pixel.
  7452. *
  7453. * Overwritten and set to `NearestFilter` by default.
  7454. *
  7455. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7456. * @default NearestFilter
  7457. */
  7458. this.minFilter = NearestFilter;
  7459. /**
  7460. * This defines how the texture is wrapped in the depth and corresponds to
  7461. * *W* in UVW mapping.
  7462. *
  7463. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7464. * @default ClampToEdgeWrapping
  7465. */
  7466. this.wrapR = ClampToEdgeWrapping;
  7467. /**
  7468. * Whether to generate mipmaps (if possible) for a texture.
  7469. *
  7470. * Overwritten and set to `false` by default.
  7471. *
  7472. * @type {boolean}
  7473. * @default false
  7474. */
  7475. this.generateMipmaps = false;
  7476. /**
  7477. * If set to `true`, the texture is flipped along the vertical axis when
  7478. * uploaded to the GPU.
  7479. *
  7480. * Overwritten and set to `false` by default.
  7481. *
  7482. * @type {boolean}
  7483. * @default false
  7484. */
  7485. this.flipY = false;
  7486. /**
  7487. * Specifies the alignment requirements for the start of each pixel row in memory.
  7488. *
  7489. * Overwritten and set to `1` by default.
  7490. *
  7491. * @type {boolean}
  7492. * @default 1
  7493. */
  7494. this.unpackAlignment = 1;
  7495. }
  7496. }
  7497. /**
  7498. * A 3D render target used in context of {@link WebGLRenderer}.
  7499. *
  7500. * @augments WebGLRenderTarget
  7501. */
  7502. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7503. /**
  7504. * Constructs a new 3D render target.
  7505. *
  7506. * @param {number} [width=1] - The width of the render target.
  7507. * @param {number} [height=1] - The height of the render target.
  7508. * @param {number} [depth=1] - The height of the render target.
  7509. * @param {RenderTarget~Options} [options] - The configuration object.
  7510. */
  7511. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7512. super( width, height, options );
  7513. /**
  7514. * This flag can be used for type testing.
  7515. *
  7516. * @type {boolean}
  7517. * @readonly
  7518. * @default true
  7519. */
  7520. this.isWebGL3DRenderTarget = true;
  7521. this.depth = depth;
  7522. /**
  7523. * Overwritten with a different texture type.
  7524. *
  7525. * @type {Data3DTexture}
  7526. */
  7527. this.texture = new Data3DTexture( null, width, height, depth );
  7528. this._setTextureOptions( options );
  7529. this.texture.isRenderTargetTexture = true;
  7530. }
  7531. }
  7532. /**
  7533. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7534. */
  7535. class Box3 {
  7536. /**
  7537. * Constructs a new bounding box.
  7538. *
  7539. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7540. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7541. */
  7542. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7543. /**
  7544. * This flag can be used for type testing.
  7545. *
  7546. * @type {boolean}
  7547. * @readonly
  7548. * @default true
  7549. */
  7550. this.isBox3 = true;
  7551. /**
  7552. * The lower boundary of the box.
  7553. *
  7554. * @type {Vector3}
  7555. */
  7556. this.min = min;
  7557. /**
  7558. * The upper boundary of the box.
  7559. *
  7560. * @type {Vector3}
  7561. */
  7562. this.max = max;
  7563. }
  7564. /**
  7565. * Sets the lower and upper boundaries of this box.
  7566. * Please note that this method only copies the values from the given objects.
  7567. *
  7568. * @param {Vector3} min - The lower boundary of the box.
  7569. * @param {Vector3} max - The upper boundary of the box.
  7570. * @return {Box3} A reference to this bounding box.
  7571. */
  7572. set( min, max ) {
  7573. this.min.copy( min );
  7574. this.max.copy( max );
  7575. return this;
  7576. }
  7577. /**
  7578. * Sets the upper and lower bounds of this box so it encloses the position data
  7579. * in the given array.
  7580. *
  7581. * @param {Array<number>} array - An array holding 3D position data.
  7582. * @return {Box3} A reference to this bounding box.
  7583. */
  7584. setFromArray( array ) {
  7585. this.makeEmpty();
  7586. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7587. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7588. }
  7589. return this;
  7590. }
  7591. /**
  7592. * Sets the upper and lower bounds of this box so it encloses the position data
  7593. * in the given buffer attribute.
  7594. *
  7595. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7596. * @return {Box3} A reference to this bounding box.
  7597. */
  7598. setFromBufferAttribute( attribute ) {
  7599. this.makeEmpty();
  7600. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7601. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7602. }
  7603. return this;
  7604. }
  7605. /**
  7606. * Sets the upper and lower bounds of this box so it encloses the position data
  7607. * in the given array.
  7608. *
  7609. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7610. * @return {Box3} A reference to this bounding box.
  7611. */
  7612. setFromPoints( points ) {
  7613. this.makeEmpty();
  7614. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7615. this.expandByPoint( points[ i ] );
  7616. }
  7617. return this;
  7618. }
  7619. /**
  7620. * Centers this box on the given center vector and sets this box's width, height and
  7621. * depth to the given size values.
  7622. *
  7623. * @param {Vector3} center - The center of the box.
  7624. * @param {Vector3} size - The x, y and z dimensions of the box.
  7625. * @return {Box3} A reference to this bounding box.
  7626. */
  7627. setFromCenterAndSize( center, size ) {
  7628. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7629. this.min.copy( center ).sub( halfSize );
  7630. this.max.copy( center ).add( halfSize );
  7631. return this;
  7632. }
  7633. /**
  7634. * Computes the world-axis-aligned bounding box for the given 3D object
  7635. * (including its children), accounting for the object's, and children's,
  7636. * world transforms. The function may result in a larger box than strictly necessary.
  7637. *
  7638. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7639. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7640. * world-axis-aligned bounding box at the expense of more computation.
  7641. * @return {Box3} A reference to this bounding box.
  7642. */
  7643. setFromObject( object, precise = false ) {
  7644. this.makeEmpty();
  7645. return this.expandByObject( object, precise );
  7646. }
  7647. /**
  7648. * Returns a new box with copied values from this instance.
  7649. *
  7650. * @return {Box3} A clone of this instance.
  7651. */
  7652. clone() {
  7653. return new this.constructor().copy( this );
  7654. }
  7655. /**
  7656. * Copies the values of the given box to this instance.
  7657. *
  7658. * @param {Box3} box - The box to copy.
  7659. * @return {Box3} A reference to this bounding box.
  7660. */
  7661. copy( box ) {
  7662. this.min.copy( box.min );
  7663. this.max.copy( box.max );
  7664. return this;
  7665. }
  7666. /**
  7667. * Makes this box empty which means in encloses a zero space in 3D.
  7668. *
  7669. * @return {Box3} A reference to this bounding box.
  7670. */
  7671. makeEmpty() {
  7672. this.min.x = this.min.y = this.min.z = + Infinity;
  7673. this.max.x = this.max.y = this.max.z = - Infinity;
  7674. return this;
  7675. }
  7676. /**
  7677. * Returns true if this box includes zero points within its bounds.
  7678. * Note that a box with equal lower and upper bounds still includes one
  7679. * point, the one both bounds share.
  7680. *
  7681. * @return {boolean} Whether this box is empty or not.
  7682. */
  7683. isEmpty() {
  7684. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7685. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7686. }
  7687. /**
  7688. * Returns the center point of this box.
  7689. *
  7690. * @param {Vector3} target - The target vector that is used to store the method's result.
  7691. * @return {Vector3} The center point.
  7692. */
  7693. getCenter( target ) {
  7694. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7695. }
  7696. /**
  7697. * Returns the dimensions of this box.
  7698. *
  7699. * @param {Vector3} target - The target vector that is used to store the method's result.
  7700. * @return {Vector3} The size.
  7701. */
  7702. getSize( target ) {
  7703. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7704. }
  7705. /**
  7706. * Expands the boundaries of this box to include the given point.
  7707. *
  7708. * @param {Vector3} point - The point that should be included by the bounding box.
  7709. * @return {Box3} A reference to this bounding box.
  7710. */
  7711. expandByPoint( point ) {
  7712. this.min.min( point );
  7713. this.max.max( point );
  7714. return this;
  7715. }
  7716. /**
  7717. * Expands this box equilaterally by the given vector. The width of this
  7718. * box will be expanded by the x component of the vector in both
  7719. * directions. The height of this box will be expanded by the y component of
  7720. * the vector in both directions. The depth of this box will be
  7721. * expanded by the z component of the vector in both directions.
  7722. *
  7723. * @param {Vector3} vector - The vector that should expand the bounding box.
  7724. * @return {Box3} A reference to this bounding box.
  7725. */
  7726. expandByVector( vector ) {
  7727. this.min.sub( vector );
  7728. this.max.add( vector );
  7729. return this;
  7730. }
  7731. /**
  7732. * Expands each dimension of the box by the given scalar. If negative, the
  7733. * dimensions of the box will be contracted.
  7734. *
  7735. * @param {number} scalar - The scalar value that should expand the bounding box.
  7736. * @return {Box3} A reference to this bounding box.
  7737. */
  7738. expandByScalar( scalar ) {
  7739. this.min.addScalar( - scalar );
  7740. this.max.addScalar( scalar );
  7741. return this;
  7742. }
  7743. /**
  7744. * Expands the boundaries of this box to include the given 3D object and
  7745. * its children, accounting for the object's, and children's, world
  7746. * transforms. The function may result in a larger box than strictly
  7747. * necessary (unless the precise parameter is set to true).
  7748. *
  7749. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7750. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7751. * as little as necessary at the expense of more computation.
  7752. * @return {Box3} A reference to this bounding box.
  7753. */
  7754. expandByObject( object, precise = false ) {
  7755. // Computes the world-axis-aligned bounding box of an object (including its children),
  7756. // accounting for both the object's, and children's, world transforms
  7757. object.updateWorldMatrix( false, false );
  7758. const geometry = object.geometry;
  7759. if ( geometry !== undefined ) {
  7760. const positionAttribute = geometry.getAttribute( 'position' );
  7761. // precise AABB computation based on vertex data requires at least a position attribute.
  7762. // instancing isn't supported so far and uses the normal (conservative) code path.
  7763. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7764. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7765. if ( object.isMesh === true ) {
  7766. object.getVertexPosition( i, _vector$b );
  7767. } else {
  7768. _vector$b.fromBufferAttribute( positionAttribute, i );
  7769. }
  7770. _vector$b.applyMatrix4( object.matrixWorld );
  7771. this.expandByPoint( _vector$b );
  7772. }
  7773. } else {
  7774. if ( object.boundingBox !== undefined ) {
  7775. // object-level bounding box
  7776. if ( object.boundingBox === null ) {
  7777. object.computeBoundingBox();
  7778. }
  7779. _box$4.copy( object.boundingBox );
  7780. } else {
  7781. // geometry-level bounding box
  7782. if ( geometry.boundingBox === null ) {
  7783. geometry.computeBoundingBox();
  7784. }
  7785. _box$4.copy( geometry.boundingBox );
  7786. }
  7787. _box$4.applyMatrix4( object.matrixWorld );
  7788. this.union( _box$4 );
  7789. }
  7790. }
  7791. const children = object.children;
  7792. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7793. this.expandByObject( children[ i ], precise );
  7794. }
  7795. return this;
  7796. }
  7797. /**
  7798. * Returns `true` if the given point lies within or on the boundaries of this box.
  7799. *
  7800. * @param {Vector3} point - The point to test.
  7801. * @return {boolean} Whether the bounding box contains the given point or not.
  7802. */
  7803. containsPoint( point ) {
  7804. return point.x >= this.min.x && point.x <= this.max.x &&
  7805. point.y >= this.min.y && point.y <= this.max.y &&
  7806. point.z >= this.min.z && point.z <= this.max.z;
  7807. }
  7808. /**
  7809. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7810. * If this box and the given one are identical, this function also returns `true`.
  7811. *
  7812. * @param {Box3} box - The bounding box to test.
  7813. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7814. */
  7815. containsBox( box ) {
  7816. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7817. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7818. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7819. }
  7820. /**
  7821. * Returns a point as a proportion of this box's width, height and depth.
  7822. *
  7823. * @param {Vector3} point - A point in 3D space.
  7824. * @param {Vector3} target - The target vector that is used to store the method's result.
  7825. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7826. */
  7827. getParameter( point, target ) {
  7828. // This can potentially have a divide by zero if the box
  7829. // has a size dimension of 0.
  7830. return target.set(
  7831. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7832. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7833. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7834. );
  7835. }
  7836. /**
  7837. * Returns `true` if the given bounding box intersects with this bounding box.
  7838. *
  7839. * @param {Box3} box - The bounding box to test.
  7840. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7841. */
  7842. intersectsBox( box ) {
  7843. // using 6 splitting planes to rule out intersections.
  7844. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7845. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7846. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7847. }
  7848. /**
  7849. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7850. *
  7851. * @param {Sphere} sphere - The bounding sphere to test.
  7852. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7853. */
  7854. intersectsSphere( sphere ) {
  7855. // Find the point on the AABB closest to the sphere center.
  7856. this.clampPoint( sphere.center, _vector$b );
  7857. // If that point is inside the sphere, the AABB and sphere intersect.
  7858. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7859. }
  7860. /**
  7861. * Returns `true` if the given plane intersects with this bounding box.
  7862. *
  7863. * @param {Plane} plane - The plane to test.
  7864. * @return {boolean} Whether the given plane intersects with this bounding box.
  7865. */
  7866. intersectsPlane( plane ) {
  7867. // We compute the minimum and maximum dot product values. If those values
  7868. // are on the same side (back or front) of the plane, then there is no intersection.
  7869. let min, max;
  7870. if ( plane.normal.x > 0 ) {
  7871. min = plane.normal.x * this.min.x;
  7872. max = plane.normal.x * this.max.x;
  7873. } else {
  7874. min = plane.normal.x * this.max.x;
  7875. max = plane.normal.x * this.min.x;
  7876. }
  7877. if ( plane.normal.y > 0 ) {
  7878. min += plane.normal.y * this.min.y;
  7879. max += plane.normal.y * this.max.y;
  7880. } else {
  7881. min += plane.normal.y * this.max.y;
  7882. max += plane.normal.y * this.min.y;
  7883. }
  7884. if ( plane.normal.z > 0 ) {
  7885. min += plane.normal.z * this.min.z;
  7886. max += plane.normal.z * this.max.z;
  7887. } else {
  7888. min += plane.normal.z * this.max.z;
  7889. max += plane.normal.z * this.min.z;
  7890. }
  7891. return ( min <= - plane.constant && max >= - plane.constant );
  7892. }
  7893. /**
  7894. * Returns `true` if the given triangle intersects with this bounding box.
  7895. *
  7896. * @param {Triangle} triangle - The triangle to test.
  7897. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7898. */
  7899. intersectsTriangle( triangle ) {
  7900. if ( this.isEmpty() ) {
  7901. return false;
  7902. }
  7903. // compute box center and extents
  7904. this.getCenter( _center );
  7905. _extents.subVectors( this.max, _center );
  7906. // translate triangle to aabb origin
  7907. _v0$2.subVectors( triangle.a, _center );
  7908. _v1$7.subVectors( triangle.b, _center );
  7909. _v2$4.subVectors( triangle.c, _center );
  7910. // compute edge vectors for triangle
  7911. _f0.subVectors( _v1$7, _v0$2 );
  7912. _f1.subVectors( _v2$4, _v1$7 );
  7913. _f2.subVectors( _v0$2, _v2$4 );
  7914. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7915. // 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
  7916. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7917. let axes = [
  7918. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7919. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7920. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7921. ];
  7922. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7923. return false;
  7924. }
  7925. // test 3 face normals from the aabb
  7926. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7927. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7928. return false;
  7929. }
  7930. // finally testing the face normal of the triangle
  7931. // use already existing triangle edge vectors here
  7932. _triangleNormal.crossVectors( _f0, _f1 );
  7933. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7934. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  7935. }
  7936. /**
  7937. * Clamps the given point within the bounds of this box.
  7938. *
  7939. * @param {Vector3} point - The point to clamp.
  7940. * @param {Vector3} target - The target vector that is used to store the method's result.
  7941. * @return {Vector3} The clamped point.
  7942. */
  7943. clampPoint( point, target ) {
  7944. return target.copy( point ).clamp( this.min, this.max );
  7945. }
  7946. /**
  7947. * Returns the euclidean distance from any edge of this box to the specified point. If
  7948. * the given point lies inside of this box, the distance will be `0`.
  7949. *
  7950. * @param {Vector3} point - The point to compute the distance to.
  7951. * @return {number} The euclidean distance.
  7952. */
  7953. distanceToPoint( point ) {
  7954. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7955. }
  7956. /**
  7957. * Returns a bounding sphere that encloses this bounding box.
  7958. *
  7959. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7960. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7961. */
  7962. getBoundingSphere( target ) {
  7963. if ( this.isEmpty() ) {
  7964. target.makeEmpty();
  7965. } else {
  7966. this.getCenter( target.center );
  7967. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7968. }
  7969. return target;
  7970. }
  7971. /**
  7972. * Computes the intersection of this bounding box and the given one, setting the upper
  7973. * bound of this box to the lesser of the two boxes' upper bounds and the
  7974. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7975. * there's no overlap, makes this box empty.
  7976. *
  7977. * @param {Box3} box - The bounding box to intersect with.
  7978. * @return {Box3} A reference to this bounding box.
  7979. */
  7980. intersect( box ) {
  7981. this.min.max( box.min );
  7982. this.max.min( box.max );
  7983. // 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.
  7984. if ( this.isEmpty() ) this.makeEmpty();
  7985. return this;
  7986. }
  7987. /**
  7988. * Computes the union of this box and another and the given one, setting the upper
  7989. * bound of this box to the greater of the two boxes' upper bounds and the
  7990. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7991. *
  7992. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7993. * @return {Box3} A reference to this bounding box.
  7994. */
  7995. union( box ) {
  7996. this.min.min( box.min );
  7997. this.max.max( box.max );
  7998. return this;
  7999. }
  8000. /**
  8001. * Transforms this bounding box by the given 4x4 transformation matrix.
  8002. *
  8003. * @param {Matrix4} matrix - The transformation matrix.
  8004. * @return {Box3} A reference to this bounding box.
  8005. */
  8006. applyMatrix4( matrix ) {
  8007. // transform of empty box is an empty box.
  8008. if ( this.isEmpty() ) return this;
  8009. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  8010. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  8011. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  8012. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  8013. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  8014. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  8015. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  8016. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  8017. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  8018. this.setFromPoints( _points );
  8019. return this;
  8020. }
  8021. /**
  8022. * Adds the given offset to both the upper and lower bounds of this bounding box,
  8023. * effectively moving it in 3D space.
  8024. *
  8025. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  8026. * @return {Box3} A reference to this bounding box.
  8027. */
  8028. translate( offset ) {
  8029. this.min.add( offset );
  8030. this.max.add( offset );
  8031. return this;
  8032. }
  8033. /**
  8034. * Returns `true` if this bounding box is equal with the given one.
  8035. *
  8036. * @param {Box3} box - The box to test for equality.
  8037. * @return {boolean} Whether this bounding box is equal with the given one.
  8038. */
  8039. equals( box ) {
  8040. return box.min.equals( this.min ) && box.max.equals( this.max );
  8041. }
  8042. /**
  8043. * Returns a serialized structure of the bounding box.
  8044. *
  8045. * @return {Object} Serialized structure with fields representing the object state.
  8046. */
  8047. toJSON() {
  8048. return {
  8049. min: this.min.toArray(),
  8050. max: this.max.toArray()
  8051. };
  8052. }
  8053. /**
  8054. * Returns a serialized structure of the bounding box.
  8055. *
  8056. * @param {Object} json - The serialized json to set the box from.
  8057. * @return {Box3} A reference to this bounding box.
  8058. */
  8059. fromJSON( json ) {
  8060. this.min.fromArray( json.min );
  8061. this.max.fromArray( json.max );
  8062. return this;
  8063. }
  8064. }
  8065. const _points = [
  8066. /*@__PURE__*/ new Vector3(),
  8067. /*@__PURE__*/ new Vector3(),
  8068. /*@__PURE__*/ new Vector3(),
  8069. /*@__PURE__*/ new Vector3(),
  8070. /*@__PURE__*/ new Vector3(),
  8071. /*@__PURE__*/ new Vector3(),
  8072. /*@__PURE__*/ new Vector3(),
  8073. /*@__PURE__*/ new Vector3()
  8074. ];
  8075. const _vector$b = /*@__PURE__*/ new Vector3();
  8076. const _box$4 = /*@__PURE__*/ new Box3();
  8077. // triangle centered vertices
  8078. const _v0$2 = /*@__PURE__*/ new Vector3();
  8079. const _v1$7 = /*@__PURE__*/ new Vector3();
  8080. const _v2$4 = /*@__PURE__*/ new Vector3();
  8081. // triangle edge vectors
  8082. const _f0 = /*@__PURE__*/ new Vector3();
  8083. const _f1 = /*@__PURE__*/ new Vector3();
  8084. const _f2 = /*@__PURE__*/ new Vector3();
  8085. const _center = /*@__PURE__*/ new Vector3();
  8086. const _extents = /*@__PURE__*/ new Vector3();
  8087. const _triangleNormal = /*@__PURE__*/ new Vector3();
  8088. const _testAxis = /*@__PURE__*/ new Vector3();
  8089. function satForAxes( axes, v0, v1, v2, extents ) {
  8090. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  8091. _testAxis.fromArray( axes, i );
  8092. // project the aabb onto the separating axis
  8093. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  8094. // project all 3 vertices of the triangle onto the separating axis
  8095. const p0 = v0.dot( _testAxis );
  8096. const p1 = v1.dot( _testAxis );
  8097. const p2 = v2.dot( _testAxis );
  8098. // actual test, basically see if either of the most extreme of the triangle points intersects r
  8099. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  8100. // points of the projected triangle are outside the projected half-length of the aabb
  8101. // the axis is separating and we can exit
  8102. return false;
  8103. }
  8104. }
  8105. return true;
  8106. }
  8107. const _box$3 = /*@__PURE__*/ new Box3();
  8108. const _v1$6 = /*@__PURE__*/ new Vector3();
  8109. const _v2$3 = /*@__PURE__*/ new Vector3();
  8110. /**
  8111. * An analytical 3D sphere defined by a center and radius. This class is mainly
  8112. * used as a Bounding Sphere for 3D objects.
  8113. */
  8114. class Sphere {
  8115. /**
  8116. * Constructs a new sphere.
  8117. *
  8118. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  8119. * @param {number} [radius=-1] - The radius of the sphere.
  8120. */
  8121. constructor( center = new Vector3(), radius = -1 ) {
  8122. /**
  8123. * This flag can be used for type testing.
  8124. *
  8125. * @type {boolean}
  8126. * @readonly
  8127. * @default true
  8128. */
  8129. this.isSphere = true;
  8130. /**
  8131. * The center of the sphere
  8132. *
  8133. * @type {Vector3}
  8134. */
  8135. this.center = center;
  8136. /**
  8137. * The radius of the sphere.
  8138. *
  8139. * @type {number}
  8140. */
  8141. this.radius = radius;
  8142. }
  8143. /**
  8144. * Sets the sphere's components by copying the given values.
  8145. *
  8146. * @param {Vector3} center - The center.
  8147. * @param {number} radius - The radius.
  8148. * @return {Sphere} A reference to this sphere.
  8149. */
  8150. set( center, radius ) {
  8151. this.center.copy( center );
  8152. this.radius = radius;
  8153. return this;
  8154. }
  8155. /**
  8156. * Computes the minimum bounding sphere for list of points.
  8157. * If the optional center point is given, it is used as the sphere's
  8158. * center. Otherwise, the center of the axis-aligned bounding box
  8159. * encompassing the points is calculated.
  8160. *
  8161. * @param {Array<Vector3>} points - A list of points in 3D space.
  8162. * @param {Vector3} [optionalCenter] - The center of the sphere.
  8163. * @return {Sphere} A reference to this sphere.
  8164. */
  8165. setFromPoints( points, optionalCenter ) {
  8166. const center = this.center;
  8167. if ( optionalCenter !== undefined ) {
  8168. center.copy( optionalCenter );
  8169. } else {
  8170. _box$3.setFromPoints( points ).getCenter( center );
  8171. }
  8172. let maxRadiusSq = 0;
  8173. for ( let i = 0, il = points.length; i < il; i ++ ) {
  8174. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  8175. }
  8176. this.radius = Math.sqrt( maxRadiusSq );
  8177. return this;
  8178. }
  8179. /**
  8180. * Copies the values of the given sphere to this instance.
  8181. *
  8182. * @param {Sphere} sphere - The sphere to copy.
  8183. * @return {Sphere} A reference to this sphere.
  8184. */
  8185. copy( sphere ) {
  8186. this.center.copy( sphere.center );
  8187. this.radius = sphere.radius;
  8188. return this;
  8189. }
  8190. /**
  8191. * Returns `true` if the sphere is empty (the radius set to a negative number).
  8192. *
  8193. * Spheres with a radius of `0` contain only their center point and are not
  8194. * considered to be empty.
  8195. *
  8196. * @return {boolean} Whether this sphere is empty or not.
  8197. */
  8198. isEmpty() {
  8199. return ( this.radius < 0 );
  8200. }
  8201. /**
  8202. * Makes this sphere empty which means in encloses a zero space in 3D.
  8203. *
  8204. * @return {Sphere} A reference to this sphere.
  8205. */
  8206. makeEmpty() {
  8207. this.center.set( 0, 0, 0 );
  8208. this.radius = -1;
  8209. return this;
  8210. }
  8211. /**
  8212. * Returns `true` if this sphere contains the given point inclusive of
  8213. * the surface of the sphere.
  8214. *
  8215. * @param {Vector3} point - The point to check.
  8216. * @return {boolean} Whether this sphere contains the given point or not.
  8217. */
  8218. containsPoint( point ) {
  8219. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  8220. }
  8221. /**
  8222. * Returns the closest distance from the boundary of the sphere to the
  8223. * given point. If the sphere contains the point, the distance will
  8224. * be negative.
  8225. *
  8226. * @param {Vector3} point - The point to compute the distance to.
  8227. * @return {number} The distance to the point.
  8228. */
  8229. distanceToPoint( point ) {
  8230. return ( point.distanceTo( this.center ) - this.radius );
  8231. }
  8232. /**
  8233. * Returns `true` if this sphere intersects with the given one.
  8234. *
  8235. * @param {Sphere} sphere - The sphere to test.
  8236. * @return {boolean} Whether this sphere intersects with the given one or not.
  8237. */
  8238. intersectsSphere( sphere ) {
  8239. const radiusSum = this.radius + sphere.radius;
  8240. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8241. }
  8242. /**
  8243. * Returns `true` if this sphere intersects with the given box.
  8244. *
  8245. * @param {Box3} box - The box to test.
  8246. * @return {boolean} Whether this sphere intersects with the given box or not.
  8247. */
  8248. intersectsBox( box ) {
  8249. return box.intersectsSphere( this );
  8250. }
  8251. /**
  8252. * Returns `true` if this sphere intersects with the given plane.
  8253. *
  8254. * @param {Plane} plane - The plane to test.
  8255. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8256. */
  8257. intersectsPlane( plane ) {
  8258. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8259. }
  8260. /**
  8261. * Clamps a point within the sphere. If the point is outside the sphere, it
  8262. * will clamp it to the closest point on the edge of the sphere. Points
  8263. * already inside the sphere will not be affected.
  8264. *
  8265. * @param {Vector3} point - The plane to clamp.
  8266. * @param {Vector3} target - The target vector that is used to store the method's result.
  8267. * @return {Vector3} The clamped point.
  8268. */
  8269. clampPoint( point, target ) {
  8270. const deltaLengthSq = this.center.distanceToSquared( point );
  8271. target.copy( point );
  8272. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8273. target.sub( this.center ).normalize();
  8274. target.multiplyScalar( this.radius ).add( this.center );
  8275. }
  8276. return target;
  8277. }
  8278. /**
  8279. * Returns a bounding box that encloses this sphere.
  8280. *
  8281. * @param {Box3} target - The target box that is used to store the method's result.
  8282. * @return {Box3} The bounding box that encloses this sphere.
  8283. */
  8284. getBoundingBox( target ) {
  8285. if ( this.isEmpty() ) {
  8286. // Empty sphere produces empty bounding box
  8287. target.makeEmpty();
  8288. return target;
  8289. }
  8290. target.set( this.center, this.center );
  8291. target.expandByScalar( this.radius );
  8292. return target;
  8293. }
  8294. /**
  8295. * Transforms this sphere with the given 4x4 transformation matrix.
  8296. *
  8297. * @param {Matrix4} matrix - The transformation matrix.
  8298. * @return {Sphere} A reference to this sphere.
  8299. */
  8300. applyMatrix4( matrix ) {
  8301. this.center.applyMatrix4( matrix );
  8302. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8303. return this;
  8304. }
  8305. /**
  8306. * Translates the sphere's center by the given offset.
  8307. *
  8308. * @param {Vector3} offset - The offset.
  8309. * @return {Sphere} A reference to this sphere.
  8310. */
  8311. translate( offset ) {
  8312. this.center.add( offset );
  8313. return this;
  8314. }
  8315. /**
  8316. * Expands the boundaries of this sphere to include the given point.
  8317. *
  8318. * @param {Vector3} point - The point to include.
  8319. * @return {Sphere} A reference to this sphere.
  8320. */
  8321. expandByPoint( point ) {
  8322. if ( this.isEmpty() ) {
  8323. this.center.copy( point );
  8324. this.radius = 0;
  8325. return this;
  8326. }
  8327. _v1$6.subVectors( point, this.center );
  8328. const lengthSq = _v1$6.lengthSq();
  8329. if ( lengthSq > ( this.radius * this.radius ) ) {
  8330. // calculate the minimal sphere
  8331. const length = Math.sqrt( lengthSq );
  8332. const delta = ( length - this.radius ) * 0.5;
  8333. this.center.addScaledVector( _v1$6, delta / length );
  8334. this.radius += delta;
  8335. }
  8336. return this;
  8337. }
  8338. /**
  8339. * Expands this sphere to enclose both the original sphere and the given sphere.
  8340. *
  8341. * @param {Sphere} sphere - The sphere to include.
  8342. * @return {Sphere} A reference to this sphere.
  8343. */
  8344. union( sphere ) {
  8345. if ( sphere.isEmpty() ) {
  8346. return this;
  8347. }
  8348. if ( this.isEmpty() ) {
  8349. this.copy( sphere );
  8350. return this;
  8351. }
  8352. if ( this.center.equals( sphere.center ) === true ) {
  8353. this.radius = Math.max( this.radius, sphere.radius );
  8354. } else {
  8355. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8356. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8357. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8358. }
  8359. return this;
  8360. }
  8361. /**
  8362. * Returns `true` if this sphere is equal with the given one.
  8363. *
  8364. * @param {Sphere} sphere - The sphere to test for equality.
  8365. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8366. */
  8367. equals( sphere ) {
  8368. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8369. }
  8370. /**
  8371. * Returns a new sphere with copied values from this instance.
  8372. *
  8373. * @return {Sphere} A clone of this instance.
  8374. */
  8375. clone() {
  8376. return new this.constructor().copy( this );
  8377. }
  8378. /**
  8379. * Returns a serialized structure of the bounding sphere.
  8380. *
  8381. * @return {Object} Serialized structure with fields representing the object state.
  8382. */
  8383. toJSON() {
  8384. return {
  8385. radius: this.radius,
  8386. center: this.center.toArray()
  8387. };
  8388. }
  8389. /**
  8390. * Returns a serialized structure of the bounding sphere.
  8391. *
  8392. * @param {Object} json - The serialized json to set the sphere from.
  8393. * @return {Sphere} A reference to this bounding sphere.
  8394. */
  8395. fromJSON( json ) {
  8396. this.radius = json.radius;
  8397. this.center.fromArray( json.center );
  8398. return this;
  8399. }
  8400. }
  8401. const _vector$a = /*@__PURE__*/ new Vector3();
  8402. const _segCenter = /*@__PURE__*/ new Vector3();
  8403. const _segDir = /*@__PURE__*/ new Vector3();
  8404. const _diff = /*@__PURE__*/ new Vector3();
  8405. const _edge1 = /*@__PURE__*/ new Vector3();
  8406. const _edge2 = /*@__PURE__*/ new Vector3();
  8407. const _normal$1 = /*@__PURE__*/ new Vector3();
  8408. /**
  8409. * A ray that emits from an origin in a certain direction. The class is used by
  8410. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8411. * mouse picking (working out what objects in the 3D space the mouse is over)
  8412. * amongst other things.
  8413. */
  8414. class Ray {
  8415. /**
  8416. * Constructs a new ray.
  8417. *
  8418. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8419. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8420. */
  8421. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8422. /**
  8423. * The origin of the ray.
  8424. *
  8425. * @type {Vector3}
  8426. */
  8427. this.origin = origin;
  8428. /**
  8429. * The (normalized) direction of the ray.
  8430. *
  8431. * @type {Vector3}
  8432. */
  8433. this.direction = direction;
  8434. }
  8435. /**
  8436. * Sets the ray's components by copying the given values.
  8437. *
  8438. * @param {Vector3} origin - The origin.
  8439. * @param {Vector3} direction - The direction.
  8440. * @return {Ray} A reference to this ray.
  8441. */
  8442. set( origin, direction ) {
  8443. this.origin.copy( origin );
  8444. this.direction.copy( direction );
  8445. return this;
  8446. }
  8447. /**
  8448. * Copies the values of the given ray to this instance.
  8449. *
  8450. * @param {Ray} ray - The ray to copy.
  8451. * @return {Ray} A reference to this ray.
  8452. */
  8453. copy( ray ) {
  8454. this.origin.copy( ray.origin );
  8455. this.direction.copy( ray.direction );
  8456. return this;
  8457. }
  8458. /**
  8459. * Returns a vector that is located at a given distance along this ray.
  8460. *
  8461. * @param {number} t - The distance along the ray to retrieve a position for.
  8462. * @param {Vector3} target - The target vector that is used to store the method's result.
  8463. * @return {Vector3} A position on the ray.
  8464. */
  8465. at( t, target ) {
  8466. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8467. }
  8468. /**
  8469. * Adjusts the direction of the ray to point at the given vector in world space.
  8470. *
  8471. * @param {Vector3} v - The target position.
  8472. * @return {Ray} A reference to this ray.
  8473. */
  8474. lookAt( v ) {
  8475. this.direction.copy( v ).sub( this.origin ).normalize();
  8476. return this;
  8477. }
  8478. /**
  8479. * Shift the origin of this ray along its direction by the given distance.
  8480. *
  8481. * @param {number} t - The distance along the ray to interpolate.
  8482. * @return {Ray} A reference to this ray.
  8483. */
  8484. recast( t ) {
  8485. this.origin.copy( this.at( t, _vector$a ) );
  8486. return this;
  8487. }
  8488. /**
  8489. * Returns the point along this ray that is closest to the given point.
  8490. *
  8491. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8492. * @param {Vector3} target - The target vector that is used to store the method's result.
  8493. * @return {Vector3} The closest point on this ray.
  8494. */
  8495. closestPointToPoint( point, target ) {
  8496. target.subVectors( point, this.origin );
  8497. const directionDistance = target.dot( this.direction );
  8498. if ( directionDistance < 0 ) {
  8499. return target.copy( this.origin );
  8500. }
  8501. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8502. }
  8503. /**
  8504. * Returns the distance of the closest approach between this ray and the given point.
  8505. *
  8506. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8507. * @return {number} The distance.
  8508. */
  8509. distanceToPoint( point ) {
  8510. return Math.sqrt( this.distanceSqToPoint( point ) );
  8511. }
  8512. /**
  8513. * Returns the squared distance of the closest approach between this ray and the given point.
  8514. *
  8515. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8516. * @return {number} The squared distance.
  8517. */
  8518. distanceSqToPoint( point ) {
  8519. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8520. // point behind the ray
  8521. if ( directionDistance < 0 ) {
  8522. return this.origin.distanceToSquared( point );
  8523. }
  8524. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8525. return _vector$a.distanceToSquared( point );
  8526. }
  8527. /**
  8528. * Returns the squared distance between this ray and the given line segment.
  8529. *
  8530. * @param {Vector3} v0 - The start point of the line segment.
  8531. * @param {Vector3} v1 - The end point of the line segment.
  8532. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8533. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8534. * @return {number} The squared distance.
  8535. */
  8536. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8537. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8538. // It returns the min distance between the ray and the segment
  8539. // defined by v0 and v1
  8540. // It can also set two optional targets :
  8541. // - The closest point on the ray
  8542. // - The closest point on the segment
  8543. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8544. _segDir.copy( v1 ).sub( v0 ).normalize();
  8545. _diff.copy( this.origin ).sub( _segCenter );
  8546. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8547. const a01 = - this.direction.dot( _segDir );
  8548. const b0 = _diff.dot( this.direction );
  8549. const b1 = - _diff.dot( _segDir );
  8550. const c = _diff.lengthSq();
  8551. const det = Math.abs( 1 - a01 * a01 );
  8552. let s0, s1, sqrDist, extDet;
  8553. if ( det > 0 ) {
  8554. // The ray and segment are not parallel.
  8555. s0 = a01 * b1 - b0;
  8556. s1 = a01 * b0 - b1;
  8557. extDet = segExtent * det;
  8558. if ( s0 >= 0 ) {
  8559. if ( s1 >= - extDet ) {
  8560. if ( s1 <= extDet ) {
  8561. // region 0
  8562. // Minimum at interior points of ray and segment.
  8563. const invDet = 1 / det;
  8564. s0 *= invDet;
  8565. s1 *= invDet;
  8566. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8567. } else {
  8568. // region 1
  8569. s1 = segExtent;
  8570. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8571. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8572. }
  8573. } else {
  8574. // region 5
  8575. s1 = - segExtent;
  8576. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8577. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8578. }
  8579. } else {
  8580. if ( s1 <= - extDet ) {
  8581. // region 4
  8582. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8583. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8584. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8585. } else if ( s1 <= extDet ) {
  8586. // region 3
  8587. s0 = 0;
  8588. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8589. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8590. } else {
  8591. // region 2
  8592. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8593. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8594. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8595. }
  8596. }
  8597. } else {
  8598. // Ray and segment are parallel.
  8599. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8600. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8601. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8602. }
  8603. if ( optionalPointOnRay ) {
  8604. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8605. }
  8606. if ( optionalPointOnSegment ) {
  8607. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8608. }
  8609. return sqrDist;
  8610. }
  8611. /**
  8612. * Intersects this ray with the given sphere, returning the intersection
  8613. * point or `null` if there is no intersection.
  8614. *
  8615. * @param {Sphere} sphere - The sphere to intersect.
  8616. * @param {Vector3} target - The target vector that is used to store the method's result.
  8617. * @return {?Vector3} The intersection point.
  8618. */
  8619. intersectSphere( sphere, target ) {
  8620. _vector$a.subVectors( sphere.center, this.origin );
  8621. const tca = _vector$a.dot( this.direction );
  8622. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8623. const radius2 = sphere.radius * sphere.radius;
  8624. if ( d2 > radius2 ) return null;
  8625. const thc = Math.sqrt( radius2 - d2 );
  8626. // t0 = first intersect point - entrance on front of sphere
  8627. const t0 = tca - thc;
  8628. // t1 = second intersect point - exit point on back of sphere
  8629. const t1 = tca + thc;
  8630. // test to see if t1 is behind the ray - if so, return null
  8631. if ( t1 < 0 ) return null;
  8632. // test to see if t0 is behind the ray:
  8633. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8634. // in order to always return an intersect point that is in front of the ray.
  8635. if ( t0 < 0 ) return this.at( t1, target );
  8636. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8637. return this.at( t0, target );
  8638. }
  8639. /**
  8640. * Returns `true` if this ray intersects with the given sphere.
  8641. *
  8642. * @param {Sphere} sphere - The sphere to intersect.
  8643. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8644. */
  8645. intersectsSphere( sphere ) {
  8646. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8647. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8648. }
  8649. /**
  8650. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8651. * does not intersect with the plane.
  8652. *
  8653. * @param {Plane} plane - The plane to compute the distance to.
  8654. * @return {?number} Whether this ray intersects with the given sphere or not.
  8655. */
  8656. distanceToPlane( plane ) {
  8657. const denominator = plane.normal.dot( this.direction );
  8658. if ( denominator === 0 ) {
  8659. // line is coplanar, return origin
  8660. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8661. return 0;
  8662. }
  8663. // Null is preferable to undefined since undefined means.... it is undefined
  8664. return null;
  8665. }
  8666. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8667. // Return if the ray never intersects the plane
  8668. return t >= 0 ? t : null;
  8669. }
  8670. /**
  8671. * Intersects this ray with the given plane, returning the intersection
  8672. * point or `null` if there is no intersection.
  8673. *
  8674. * @param {Plane} plane - The plane to intersect.
  8675. * @param {Vector3} target - The target vector that is used to store the method's result.
  8676. * @return {?Vector3} The intersection point.
  8677. */
  8678. intersectPlane( plane, target ) {
  8679. const t = this.distanceToPlane( plane );
  8680. if ( t === null ) {
  8681. return null;
  8682. }
  8683. return this.at( t, target );
  8684. }
  8685. /**
  8686. * Returns `true` if this ray intersects with the given plane.
  8687. *
  8688. * @param {Plane} plane - The plane to intersect.
  8689. * @return {boolean} Whether this ray intersects with the given plane or not.
  8690. */
  8691. intersectsPlane( plane ) {
  8692. // check if the ray lies on the plane first
  8693. const distToPoint = plane.distanceToPoint( this.origin );
  8694. if ( distToPoint === 0 ) {
  8695. return true;
  8696. }
  8697. const denominator = plane.normal.dot( this.direction );
  8698. if ( denominator * distToPoint < 0 ) {
  8699. return true;
  8700. }
  8701. // ray origin is behind the plane (and is pointing behind it)
  8702. return false;
  8703. }
  8704. /**
  8705. * Intersects this ray with the given bounding box, returning the intersection
  8706. * point or `null` if there is no intersection.
  8707. *
  8708. * @param {Box3} box - The box to intersect.
  8709. * @param {Vector3} target - The target vector that is used to store the method's result.
  8710. * @return {?Vector3} The intersection point.
  8711. */
  8712. intersectBox( box, target ) {
  8713. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8714. const invdirx = 1 / this.direction.x,
  8715. invdiry = 1 / this.direction.y,
  8716. invdirz = 1 / this.direction.z;
  8717. const origin = this.origin;
  8718. if ( invdirx >= 0 ) {
  8719. tmin = ( box.min.x - origin.x ) * invdirx;
  8720. tmax = ( box.max.x - origin.x ) * invdirx;
  8721. } else {
  8722. tmin = ( box.max.x - origin.x ) * invdirx;
  8723. tmax = ( box.min.x - origin.x ) * invdirx;
  8724. }
  8725. if ( invdiry >= 0 ) {
  8726. tymin = ( box.min.y - origin.y ) * invdiry;
  8727. tymax = ( box.max.y - origin.y ) * invdiry;
  8728. } else {
  8729. tymin = ( box.max.y - origin.y ) * invdiry;
  8730. tymax = ( box.min.y - origin.y ) * invdiry;
  8731. }
  8732. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8733. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8734. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8735. if ( invdirz >= 0 ) {
  8736. tzmin = ( box.min.z - origin.z ) * invdirz;
  8737. tzmax = ( box.max.z - origin.z ) * invdirz;
  8738. } else {
  8739. tzmin = ( box.max.z - origin.z ) * invdirz;
  8740. tzmax = ( box.min.z - origin.z ) * invdirz;
  8741. }
  8742. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8743. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8744. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8745. //return point closest to the ray (positive side)
  8746. if ( tmax < 0 ) return null;
  8747. return this.at( tmin >= 0 ? tmin : tmax, target );
  8748. }
  8749. /**
  8750. * Returns `true` if this ray intersects with the given box.
  8751. *
  8752. * @param {Box3} box - The box to intersect.
  8753. * @return {boolean} Whether this ray intersects with the given box or not.
  8754. */
  8755. intersectsBox( box ) {
  8756. return this.intersectBox( box, _vector$a ) !== null;
  8757. }
  8758. /**
  8759. * Intersects this ray with the given triangle, returning the intersection
  8760. * point or `null` if there is no intersection.
  8761. *
  8762. * @param {Vector3} a - The first vertex of the triangle.
  8763. * @param {Vector3} b - The second vertex of the triangle.
  8764. * @param {Vector3} c - The third vertex of the triangle.
  8765. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8766. * @param {Vector3} target - The target vector that is used to store the method's result.
  8767. * @return {?Vector3} The intersection point.
  8768. */
  8769. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8770. // Compute the offset origin, edges, and normal.
  8771. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8772. _edge1.subVectors( b, a );
  8773. _edge2.subVectors( c, a );
  8774. _normal$1.crossVectors( _edge1, _edge2 );
  8775. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8776. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8777. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8778. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8779. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8780. let DdN = this.direction.dot( _normal$1 );
  8781. let sign;
  8782. if ( DdN > 0 ) {
  8783. if ( backfaceCulling ) return null;
  8784. sign = 1;
  8785. } else if ( DdN < 0 ) {
  8786. sign = -1;
  8787. DdN = - DdN;
  8788. } else {
  8789. return null;
  8790. }
  8791. _diff.subVectors( this.origin, a );
  8792. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8793. // b1 < 0, no intersection
  8794. if ( DdQxE2 < 0 ) {
  8795. return null;
  8796. }
  8797. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8798. // b2 < 0, no intersection
  8799. if ( DdE1xQ < 0 ) {
  8800. return null;
  8801. }
  8802. // b1+b2 > 1, no intersection
  8803. if ( DdQxE2 + DdE1xQ > DdN ) {
  8804. return null;
  8805. }
  8806. // Line intersects triangle, check if ray does.
  8807. const QdN = - sign * _diff.dot( _normal$1 );
  8808. // t < 0, no intersection
  8809. if ( QdN < 0 ) {
  8810. return null;
  8811. }
  8812. // Ray intersects triangle.
  8813. return this.at( QdN / DdN, target );
  8814. }
  8815. /**
  8816. * Transforms this ray with the given 4x4 transformation matrix.
  8817. *
  8818. * @param {Matrix4} matrix4 - The transformation matrix.
  8819. * @return {Ray} A reference to this ray.
  8820. */
  8821. applyMatrix4( matrix4 ) {
  8822. this.origin.applyMatrix4( matrix4 );
  8823. this.direction.transformDirection( matrix4 );
  8824. return this;
  8825. }
  8826. /**
  8827. * Returns `true` if this ray is equal with the given one.
  8828. *
  8829. * @param {Ray} ray - The ray to test for equality.
  8830. * @return {boolean} Whether this ray is equal with the given one.
  8831. */
  8832. equals( ray ) {
  8833. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8834. }
  8835. /**
  8836. * Returns a new ray with copied values from this instance.
  8837. *
  8838. * @return {Ray} A clone of this instance.
  8839. */
  8840. clone() {
  8841. return new this.constructor().copy( this );
  8842. }
  8843. }
  8844. /**
  8845. * Represents a 4x4 matrix.
  8846. *
  8847. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8848. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  8849. *
  8850. * This allows a 3D vector representing a point in 3D space to undergo
  8851. * transformations such as translation, rotation, shear, scale, reflection,
  8852. * orthogonal or perspective projection and so on, by being multiplied by the
  8853. * matrix. This is known as `applying` the matrix to the vector.
  8854. *
  8855. * A Note on Row-Major and Column-Major Ordering:
  8856. *
  8857. * The constructor and {@link Matrix3#set} method take arguments in
  8858. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  8859. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8860. * This means that calling:
  8861. * ```js
  8862. * const m = new THREE.Matrix4();
  8863. * m.set( 11, 12, 13, 14,
  8864. * 21, 22, 23, 24,
  8865. * 31, 32, 33, 34,
  8866. * 41, 42, 43, 44 );
  8867. * ```
  8868. * will result in the elements array containing:
  8869. * ```js
  8870. * m.elements = [ 11, 21, 31, 41,
  8871. * 12, 22, 32, 42,
  8872. * 13, 23, 33, 43,
  8873. * 14, 24, 34, 44 ];
  8874. * ```
  8875. * and internally all calculations are performed using column-major ordering.
  8876. * However, as the actual ordering makes no difference mathematically and
  8877. * most people are used to thinking about matrices in row-major order, the
  8878. * three.js documentation shows matrices in row-major order. Just bear in
  8879. * mind that if you are reading the source code, you'll have to take the
  8880. * transpose of any matrices outlined here to make sense of the calculations.
  8881. */
  8882. class Matrix4 {
  8883. /**
  8884. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8885. * in row-major order. If no arguments are provided, the constructor
  8886. * initializes the matrix as an identity matrix.
  8887. *
  8888. * @param {number} [n11] - 1-1 matrix element.
  8889. * @param {number} [n12] - 1-2 matrix element.
  8890. * @param {number} [n13] - 1-3 matrix element.
  8891. * @param {number} [n14] - 1-4 matrix element.
  8892. * @param {number} [n21] - 2-1 matrix element.
  8893. * @param {number} [n22] - 2-2 matrix element.
  8894. * @param {number} [n23] - 2-3 matrix element.
  8895. * @param {number} [n24] - 2-4 matrix element.
  8896. * @param {number} [n31] - 3-1 matrix element.
  8897. * @param {number} [n32] - 3-2 matrix element.
  8898. * @param {number} [n33] - 3-3 matrix element.
  8899. * @param {number} [n34] - 3-4 matrix element.
  8900. * @param {number} [n41] - 4-1 matrix element.
  8901. * @param {number} [n42] - 4-2 matrix element.
  8902. * @param {number} [n43] - 4-3 matrix element.
  8903. * @param {number} [n44] - 4-4 matrix element.
  8904. */
  8905. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8906. /**
  8907. * This flag can be used for type testing.
  8908. *
  8909. * @type {boolean}
  8910. * @readonly
  8911. * @default true
  8912. */
  8913. Matrix4.prototype.isMatrix4 = true;
  8914. /**
  8915. * A column-major list of matrix values.
  8916. *
  8917. * @type {Array<number>}
  8918. */
  8919. this.elements = [
  8920. 1, 0, 0, 0,
  8921. 0, 1, 0, 0,
  8922. 0, 0, 1, 0,
  8923. 0, 0, 0, 1
  8924. ];
  8925. if ( n11 !== undefined ) {
  8926. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8927. }
  8928. }
  8929. /**
  8930. * Sets the elements of the matrix.The arguments are supposed to be
  8931. * in row-major order.
  8932. *
  8933. * @param {number} [n11] - 1-1 matrix element.
  8934. * @param {number} [n12] - 1-2 matrix element.
  8935. * @param {number} [n13] - 1-3 matrix element.
  8936. * @param {number} [n14] - 1-4 matrix element.
  8937. * @param {number} [n21] - 2-1 matrix element.
  8938. * @param {number} [n22] - 2-2 matrix element.
  8939. * @param {number} [n23] - 2-3 matrix element.
  8940. * @param {number} [n24] - 2-4 matrix element.
  8941. * @param {number} [n31] - 3-1 matrix element.
  8942. * @param {number} [n32] - 3-2 matrix element.
  8943. * @param {number} [n33] - 3-3 matrix element.
  8944. * @param {number} [n34] - 3-4 matrix element.
  8945. * @param {number} [n41] - 4-1 matrix element.
  8946. * @param {number} [n42] - 4-2 matrix element.
  8947. * @param {number} [n43] - 4-3 matrix element.
  8948. * @param {number} [n44] - 4-4 matrix element.
  8949. * @return {Matrix4} A reference to this matrix.
  8950. */
  8951. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8952. const te = this.elements;
  8953. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8954. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8955. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8956. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8957. return this;
  8958. }
  8959. /**
  8960. * Sets this matrix to the 4x4 identity matrix.
  8961. *
  8962. * @return {Matrix4} A reference to this matrix.
  8963. */
  8964. identity() {
  8965. this.set(
  8966. 1, 0, 0, 0,
  8967. 0, 1, 0, 0,
  8968. 0, 0, 1, 0,
  8969. 0, 0, 0, 1
  8970. );
  8971. return this;
  8972. }
  8973. /**
  8974. * Returns a matrix with copied values from this instance.
  8975. *
  8976. * @return {Matrix4} A clone of this instance.
  8977. */
  8978. clone() {
  8979. return new Matrix4().fromArray( this.elements );
  8980. }
  8981. /**
  8982. * Copies the values of the given matrix to this instance.
  8983. *
  8984. * @param {Matrix4} m - The matrix to copy.
  8985. * @return {Matrix4} A reference to this matrix.
  8986. */
  8987. copy( m ) {
  8988. const te = this.elements;
  8989. const me = m.elements;
  8990. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8991. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8992. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8993. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8994. return this;
  8995. }
  8996. /**
  8997. * Copies the translation component of the given matrix
  8998. * into this matrix's translation component.
  8999. *
  9000. * @param {Matrix4} m - The matrix to copy the translation component.
  9001. * @return {Matrix4} A reference to this matrix.
  9002. */
  9003. copyPosition( m ) {
  9004. const te = this.elements, me = m.elements;
  9005. te[ 12 ] = me[ 12 ];
  9006. te[ 13 ] = me[ 13 ];
  9007. te[ 14 ] = me[ 14 ];
  9008. return this;
  9009. }
  9010. /**
  9011. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  9012. *
  9013. * @param {Matrix3} m - The 3x3 matrix.
  9014. * @return {Matrix4} A reference to this matrix.
  9015. */
  9016. setFromMatrix3( m ) {
  9017. const me = m.elements;
  9018. this.set(
  9019. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  9020. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  9021. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  9022. 0, 0, 0, 1
  9023. );
  9024. return this;
  9025. }
  9026. /**
  9027. * Extracts the basis of this matrix into the three axis vectors provided.
  9028. *
  9029. * @param {Vector3} xAxis - The basis's x axis.
  9030. * @param {Vector3} yAxis - The basis's y axis.
  9031. * @param {Vector3} zAxis - The basis's z axis.
  9032. * @return {Matrix4} A reference to this matrix.
  9033. */
  9034. extractBasis( xAxis, yAxis, zAxis ) {
  9035. if ( this.determinant() === 0 ) {
  9036. xAxis.set( 1, 0, 0 );
  9037. yAxis.set( 0, 1, 0 );
  9038. zAxis.set( 0, 0, 1 );
  9039. return this;
  9040. }
  9041. xAxis.setFromMatrixColumn( this, 0 );
  9042. yAxis.setFromMatrixColumn( this, 1 );
  9043. zAxis.setFromMatrixColumn( this, 2 );
  9044. return this;
  9045. }
  9046. /**
  9047. * Sets the given basis vectors to this matrix.
  9048. *
  9049. * @param {Vector3} xAxis - The basis's x axis.
  9050. * @param {Vector3} yAxis - The basis's y axis.
  9051. * @param {Vector3} zAxis - The basis's z axis.
  9052. * @return {Matrix4} A reference to this matrix.
  9053. */
  9054. makeBasis( xAxis, yAxis, zAxis ) {
  9055. this.set(
  9056. xAxis.x, yAxis.x, zAxis.x, 0,
  9057. xAxis.y, yAxis.y, zAxis.y, 0,
  9058. xAxis.z, yAxis.z, zAxis.z, 0,
  9059. 0, 0, 0, 1
  9060. );
  9061. return this;
  9062. }
  9063. /**
  9064. * Extracts the rotation component of the given matrix
  9065. * into this matrix's rotation component.
  9066. *
  9067. * Note: This method does not support reflection matrices.
  9068. *
  9069. * @param {Matrix4} m - The matrix.
  9070. * @return {Matrix4} A reference to this matrix.
  9071. */
  9072. extractRotation( m ) {
  9073. if ( m.determinant() === 0 ) {
  9074. return this.identity();
  9075. }
  9076. const te = this.elements;
  9077. const me = m.elements;
  9078. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  9079. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  9080. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  9081. te[ 0 ] = me[ 0 ] * scaleX;
  9082. te[ 1 ] = me[ 1 ] * scaleX;
  9083. te[ 2 ] = me[ 2 ] * scaleX;
  9084. te[ 3 ] = 0;
  9085. te[ 4 ] = me[ 4 ] * scaleY;
  9086. te[ 5 ] = me[ 5 ] * scaleY;
  9087. te[ 6 ] = me[ 6 ] * scaleY;
  9088. te[ 7 ] = 0;
  9089. te[ 8 ] = me[ 8 ] * scaleZ;
  9090. te[ 9 ] = me[ 9 ] * scaleZ;
  9091. te[ 10 ] = me[ 10 ] * scaleZ;
  9092. te[ 11 ] = 0;
  9093. te[ 12 ] = 0;
  9094. te[ 13 ] = 0;
  9095. te[ 14 ] = 0;
  9096. te[ 15 ] = 1;
  9097. return this;
  9098. }
  9099. /**
  9100. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  9101. * the rotation specified by the given Euler angles. The rest of
  9102. * the matrix is set to the identity. Depending on the {@link Euler#order},
  9103. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  9104. * for a complete list.
  9105. *
  9106. * @param {Euler} euler - The Euler angles.
  9107. * @return {Matrix4} A reference to this matrix.
  9108. */
  9109. makeRotationFromEuler( euler ) {
  9110. const te = this.elements;
  9111. const x = euler.x, y = euler.y, z = euler.z;
  9112. const a = Math.cos( x ), b = Math.sin( x );
  9113. const c = Math.cos( y ), d = Math.sin( y );
  9114. const e = Math.cos( z ), f = Math.sin( z );
  9115. if ( euler.order === 'XYZ' ) {
  9116. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  9117. te[ 0 ] = c * e;
  9118. te[ 4 ] = - c * f;
  9119. te[ 8 ] = d;
  9120. te[ 1 ] = af + be * d;
  9121. te[ 5 ] = ae - bf * d;
  9122. te[ 9 ] = - b * c;
  9123. te[ 2 ] = bf - ae * d;
  9124. te[ 6 ] = be + af * d;
  9125. te[ 10 ] = a * c;
  9126. } else if ( euler.order === 'YXZ' ) {
  9127. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  9128. te[ 0 ] = ce + df * b;
  9129. te[ 4 ] = de * b - cf;
  9130. te[ 8 ] = a * d;
  9131. te[ 1 ] = a * f;
  9132. te[ 5 ] = a * e;
  9133. te[ 9 ] = - b;
  9134. te[ 2 ] = cf * b - de;
  9135. te[ 6 ] = df + ce * b;
  9136. te[ 10 ] = a * c;
  9137. } else if ( euler.order === 'ZXY' ) {
  9138. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  9139. te[ 0 ] = ce - df * b;
  9140. te[ 4 ] = - a * f;
  9141. te[ 8 ] = de + cf * b;
  9142. te[ 1 ] = cf + de * b;
  9143. te[ 5 ] = a * e;
  9144. te[ 9 ] = df - ce * b;
  9145. te[ 2 ] = - a * d;
  9146. te[ 6 ] = b;
  9147. te[ 10 ] = a * c;
  9148. } else if ( euler.order === 'ZYX' ) {
  9149. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  9150. te[ 0 ] = c * e;
  9151. te[ 4 ] = be * d - af;
  9152. te[ 8 ] = ae * d + bf;
  9153. te[ 1 ] = c * f;
  9154. te[ 5 ] = bf * d + ae;
  9155. te[ 9 ] = af * d - be;
  9156. te[ 2 ] = - d;
  9157. te[ 6 ] = b * c;
  9158. te[ 10 ] = a * c;
  9159. } else if ( euler.order === 'YZX' ) {
  9160. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9161. te[ 0 ] = c * e;
  9162. te[ 4 ] = bd - ac * f;
  9163. te[ 8 ] = bc * f + ad;
  9164. te[ 1 ] = f;
  9165. te[ 5 ] = a * e;
  9166. te[ 9 ] = - b * e;
  9167. te[ 2 ] = - d * e;
  9168. te[ 6 ] = ad * f + bc;
  9169. te[ 10 ] = ac - bd * f;
  9170. } else if ( euler.order === 'XZY' ) {
  9171. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9172. te[ 0 ] = c * e;
  9173. te[ 4 ] = - f;
  9174. te[ 8 ] = d * e;
  9175. te[ 1 ] = ac * f + bd;
  9176. te[ 5 ] = a * e;
  9177. te[ 9 ] = ad * f - bc;
  9178. te[ 2 ] = bc * f - ad;
  9179. te[ 6 ] = b * e;
  9180. te[ 10 ] = bd * f + ac;
  9181. }
  9182. // bottom row
  9183. te[ 3 ] = 0;
  9184. te[ 7 ] = 0;
  9185. te[ 11 ] = 0;
  9186. // last column
  9187. te[ 12 ] = 0;
  9188. te[ 13 ] = 0;
  9189. te[ 14 ] = 0;
  9190. te[ 15 ] = 1;
  9191. return this;
  9192. }
  9193. /**
  9194. * Sets the rotation component of this matrix to the rotation specified by
  9195. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  9196. * The rest of the matrix is set to the identity.
  9197. *
  9198. * @param {Quaternion} q - The Quaternion.
  9199. * @return {Matrix4} A reference to this matrix.
  9200. */
  9201. makeRotationFromQuaternion( q ) {
  9202. return this.compose( _zero, q, _one );
  9203. }
  9204. /**
  9205. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  9206. * `target`, and oriented by the up-direction.
  9207. *
  9208. * @param {Vector3} eye - The eye vector.
  9209. * @param {Vector3} target - The target vector.
  9210. * @param {Vector3} up - The up vector.
  9211. * @return {Matrix4} A reference to this matrix.
  9212. */
  9213. lookAt( eye, target, up ) {
  9214. const te = this.elements;
  9215. _z.subVectors( eye, target );
  9216. if ( _z.lengthSq() === 0 ) {
  9217. // eye and target are in the same position
  9218. _z.z = 1;
  9219. }
  9220. _z.normalize();
  9221. _x.crossVectors( up, _z );
  9222. if ( _x.lengthSq() === 0 ) {
  9223. // up and z are parallel
  9224. if ( Math.abs( up.z ) === 1 ) {
  9225. _z.x += 0.0001;
  9226. } else {
  9227. _z.z += 0.0001;
  9228. }
  9229. _z.normalize();
  9230. _x.crossVectors( up, _z );
  9231. }
  9232. _x.normalize();
  9233. _y.crossVectors( _z, _x );
  9234. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  9235. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  9236. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  9237. return this;
  9238. }
  9239. /**
  9240. * Post-multiplies this matrix by the given 4x4 matrix.
  9241. *
  9242. * @param {Matrix4} m - The matrix to multiply with.
  9243. * @return {Matrix4} A reference to this matrix.
  9244. */
  9245. multiply( m ) {
  9246. return this.multiplyMatrices( this, m );
  9247. }
  9248. /**
  9249. * Pre-multiplies this matrix by the given 4x4 matrix.
  9250. *
  9251. * @param {Matrix4} m - The matrix to multiply with.
  9252. * @return {Matrix4} A reference to this matrix.
  9253. */
  9254. premultiply( m ) {
  9255. return this.multiplyMatrices( m, this );
  9256. }
  9257. /**
  9258. * Multiples the given 4x4 matrices and stores the result
  9259. * in this matrix.
  9260. *
  9261. * @param {Matrix4} a - The first matrix.
  9262. * @param {Matrix4} b - The second matrix.
  9263. * @return {Matrix4} A reference to this matrix.
  9264. */
  9265. multiplyMatrices( a, b ) {
  9266. const ae = a.elements;
  9267. const be = b.elements;
  9268. const te = this.elements;
  9269. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9270. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9271. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9272. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9273. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9274. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9275. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9276. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9277. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9278. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9279. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9280. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9281. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9282. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9283. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9284. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9285. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9286. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9287. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9288. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9289. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9290. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9291. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9292. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9293. return this;
  9294. }
  9295. /**
  9296. * Multiplies every component of the matrix by the given scalar.
  9297. *
  9298. * @param {number} s - The scalar.
  9299. * @return {Matrix4} A reference to this matrix.
  9300. */
  9301. multiplyScalar( s ) {
  9302. const te = this.elements;
  9303. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9304. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9305. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9306. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9307. return this;
  9308. }
  9309. /**
  9310. * Computes and returns the determinant of this matrix.
  9311. *
  9312. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  9313. *
  9314. * @return {number} The determinant.
  9315. */
  9316. determinant() {
  9317. const te = this.elements;
  9318. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9319. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9320. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9321. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9322. const t11 = n23 * n34 - n24 * n33;
  9323. const t12 = n22 * n34 - n24 * n32;
  9324. const t13 = n22 * n33 - n23 * n32;
  9325. const t21 = n21 * n34 - n24 * n31;
  9326. const t22 = n21 * n33 - n23 * n31;
  9327. const t23 = n21 * n32 - n22 * n31;
  9328. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  9329. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  9330. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  9331. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  9332. }
  9333. /**
  9334. * Transposes this matrix in place.
  9335. *
  9336. * @return {Matrix4} A reference to this matrix.
  9337. */
  9338. transpose() {
  9339. const te = this.elements;
  9340. let tmp;
  9341. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9342. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9343. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9344. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9345. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9346. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9347. return this;
  9348. }
  9349. /**
  9350. * Sets the position component for this matrix from the given vector,
  9351. * without affecting the rest of the matrix.
  9352. *
  9353. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9354. * @param {number} y - The y component of the vector.
  9355. * @param {number} z - The z component of the vector.
  9356. * @return {Matrix4} A reference to this matrix.
  9357. */
  9358. setPosition( x, y, z ) {
  9359. const te = this.elements;
  9360. if ( x.isVector3 ) {
  9361. te[ 12 ] = x.x;
  9362. te[ 13 ] = x.y;
  9363. te[ 14 ] = x.z;
  9364. } else {
  9365. te[ 12 ] = x;
  9366. te[ 13 ] = y;
  9367. te[ 14 ] = z;
  9368. }
  9369. return this;
  9370. }
  9371. /**
  9372. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  9373. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9374. * a zero matrix instead.
  9375. *
  9376. * @return {Matrix4} A reference to this matrix.
  9377. */
  9378. invert() {
  9379. // based on https://github.com/toji/gl-matrix
  9380. const te = this.elements,
  9381. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9382. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9383. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9384. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9385. t1 = n11 * n22 - n21 * n12,
  9386. t2 = n11 * n32 - n31 * n12,
  9387. t3 = n11 * n42 - n41 * n12,
  9388. t4 = n21 * n32 - n31 * n22,
  9389. t5 = n21 * n42 - n41 * n22,
  9390. t6 = n31 * n42 - n41 * n32,
  9391. t7 = n13 * n24 - n23 * n14,
  9392. t8 = n13 * n34 - n33 * n14,
  9393. t9 = n13 * n44 - n43 * n14,
  9394. t10 = n23 * n34 - n33 * n24,
  9395. t11 = n23 * n44 - n43 * n24,
  9396. t12 = n33 * n44 - n43 * n34;
  9397. const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7;
  9398. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9399. const detInv = 1 / det;
  9400. te[ 0 ] = ( n22 * t12 - n32 * t11 + n42 * t10 ) * detInv;
  9401. te[ 1 ] = ( n31 * t11 - n21 * t12 - n41 * t10 ) * detInv;
  9402. te[ 2 ] = ( n24 * t6 - n34 * t5 + n44 * t4 ) * detInv;
  9403. te[ 3 ] = ( n33 * t5 - n23 * t6 - n43 * t4 ) * detInv;
  9404. te[ 4 ] = ( n32 * t9 - n12 * t12 - n42 * t8 ) * detInv;
  9405. te[ 5 ] = ( n11 * t12 - n31 * t9 + n41 * t8 ) * detInv;
  9406. te[ 6 ] = ( n34 * t3 - n14 * t6 - n44 * t2 ) * detInv;
  9407. te[ 7 ] = ( n13 * t6 - n33 * t3 + n43 * t2 ) * detInv;
  9408. te[ 8 ] = ( n12 * t11 - n22 * t9 + n42 * t7 ) * detInv;
  9409. te[ 9 ] = ( n21 * t9 - n11 * t11 - n41 * t7 ) * detInv;
  9410. te[ 10 ] = ( n14 * t5 - n24 * t3 + n44 * t1 ) * detInv;
  9411. te[ 11 ] = ( n23 * t3 - n13 * t5 - n43 * t1 ) * detInv;
  9412. te[ 12 ] = ( n22 * t8 - n12 * t10 - n32 * t7 ) * detInv;
  9413. te[ 13 ] = ( n11 * t10 - n21 * t8 + n31 * t7 ) * detInv;
  9414. te[ 14 ] = ( n24 * t2 - n14 * t4 - n34 * t1 ) * detInv;
  9415. te[ 15 ] = ( n13 * t4 - n23 * t2 + n33 * t1 ) * detInv;
  9416. return this;
  9417. }
  9418. /**
  9419. * Multiplies the columns of this matrix by the given vector.
  9420. *
  9421. * @param {Vector3} v - The scale vector.
  9422. * @return {Matrix4} A reference to this matrix.
  9423. */
  9424. scale( v ) {
  9425. const te = this.elements;
  9426. const x = v.x, y = v.y, z = v.z;
  9427. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9428. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9429. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9430. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9431. return this;
  9432. }
  9433. /**
  9434. * Gets the maximum scale value of the three axes.
  9435. *
  9436. * @return {number} The maximum scale.
  9437. */
  9438. getMaxScaleOnAxis() {
  9439. const te = this.elements;
  9440. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9441. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9442. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9443. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9444. }
  9445. /**
  9446. * Sets this matrix as a translation transform from the given vector.
  9447. *
  9448. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9449. * @param {number} y - The amount to translate in the Y axis.
  9450. * @param {number} z - The amount to translate in the z axis.
  9451. * @return {Matrix4} A reference to this matrix.
  9452. */
  9453. makeTranslation( x, y, z ) {
  9454. if ( x.isVector3 ) {
  9455. this.set(
  9456. 1, 0, 0, x.x,
  9457. 0, 1, 0, x.y,
  9458. 0, 0, 1, x.z,
  9459. 0, 0, 0, 1
  9460. );
  9461. } else {
  9462. this.set(
  9463. 1, 0, 0, x,
  9464. 0, 1, 0, y,
  9465. 0, 0, 1, z,
  9466. 0, 0, 0, 1
  9467. );
  9468. }
  9469. return this;
  9470. }
  9471. /**
  9472. * Sets this matrix as a rotational transformation around the X axis by
  9473. * the given angle.
  9474. *
  9475. * @param {number} theta - The rotation in radians.
  9476. * @return {Matrix4} A reference to this matrix.
  9477. */
  9478. makeRotationX( theta ) {
  9479. const c = Math.cos( theta ), s = Math.sin( theta );
  9480. this.set(
  9481. 1, 0, 0, 0,
  9482. 0, c, - s, 0,
  9483. 0, s, c, 0,
  9484. 0, 0, 0, 1
  9485. );
  9486. return this;
  9487. }
  9488. /**
  9489. * Sets this matrix as a rotational transformation around the Y axis by
  9490. * the given angle.
  9491. *
  9492. * @param {number} theta - The rotation in radians.
  9493. * @return {Matrix4} A reference to this matrix.
  9494. */
  9495. makeRotationY( theta ) {
  9496. const c = Math.cos( theta ), s = Math.sin( theta );
  9497. this.set(
  9498. c, 0, s, 0,
  9499. 0, 1, 0, 0,
  9500. - s, 0, c, 0,
  9501. 0, 0, 0, 1
  9502. );
  9503. return this;
  9504. }
  9505. /**
  9506. * Sets this matrix as a rotational transformation around the Z axis by
  9507. * the given angle.
  9508. *
  9509. * @param {number} theta - The rotation in radians.
  9510. * @return {Matrix4} A reference to this matrix.
  9511. */
  9512. makeRotationZ( theta ) {
  9513. const c = Math.cos( theta ), s = Math.sin( theta );
  9514. this.set(
  9515. c, - s, 0, 0,
  9516. s, c, 0, 0,
  9517. 0, 0, 1, 0,
  9518. 0, 0, 0, 1
  9519. );
  9520. return this;
  9521. }
  9522. /**
  9523. * Sets this matrix as a rotational transformation around the given axis by
  9524. * the given angle.
  9525. *
  9526. * This is a somewhat controversial but mathematically sound alternative to
  9527. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  9528. *
  9529. * @param {Vector3} axis - The normalized rotation axis.
  9530. * @param {number} angle - The rotation in radians.
  9531. * @return {Matrix4} A reference to this matrix.
  9532. */
  9533. makeRotationAxis( axis, angle ) {
  9534. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9535. const c = Math.cos( angle );
  9536. const s = Math.sin( angle );
  9537. const t = 1 - c;
  9538. const x = axis.x, y = axis.y, z = axis.z;
  9539. const tx = t * x, ty = t * y;
  9540. this.set(
  9541. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9542. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9543. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9544. 0, 0, 0, 1
  9545. );
  9546. return this;
  9547. }
  9548. /**
  9549. * Sets this matrix as a scale transformation.
  9550. *
  9551. * @param {number} x - The amount to scale in the X axis.
  9552. * @param {number} y - The amount to scale in the Y axis.
  9553. * @param {number} z - The amount to scale in the Z axis.
  9554. * @return {Matrix4} A reference to this matrix.
  9555. */
  9556. makeScale( x, y, z ) {
  9557. this.set(
  9558. x, 0, 0, 0,
  9559. 0, y, 0, 0,
  9560. 0, 0, z, 0,
  9561. 0, 0, 0, 1
  9562. );
  9563. return this;
  9564. }
  9565. /**
  9566. * Sets this matrix as a shear transformation.
  9567. *
  9568. * @param {number} xy - The amount to shear X by Y.
  9569. * @param {number} xz - The amount to shear X by Z.
  9570. * @param {number} yx - The amount to shear Y by X.
  9571. * @param {number} yz - The amount to shear Y by Z.
  9572. * @param {number} zx - The amount to shear Z by X.
  9573. * @param {number} zy - The amount to shear Z by Y.
  9574. * @return {Matrix4} A reference to this matrix.
  9575. */
  9576. makeShear( xy, xz, yx, yz, zx, zy ) {
  9577. this.set(
  9578. 1, yx, zx, 0,
  9579. xy, 1, zy, 0,
  9580. xz, yz, 1, 0,
  9581. 0, 0, 0, 1
  9582. );
  9583. return this;
  9584. }
  9585. /**
  9586. * Sets this matrix to the transformation composed of the given position,
  9587. * rotation (Quaternion) and scale.
  9588. *
  9589. * @param {Vector3} position - The position vector.
  9590. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9591. * @param {Vector3} scale - The scale vector.
  9592. * @return {Matrix4} A reference to this matrix.
  9593. */
  9594. compose( position, quaternion, scale ) {
  9595. const te = this.elements;
  9596. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9597. const x2 = x + x, y2 = y + y, z2 = z + z;
  9598. const xx = x * x2, xy = x * y2, xz = x * z2;
  9599. const yy = y * y2, yz = y * z2, zz = z * z2;
  9600. const wx = w * x2, wy = w * y2, wz = w * z2;
  9601. const sx = scale.x, sy = scale.y, sz = scale.z;
  9602. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9603. te[ 1 ] = ( xy + wz ) * sx;
  9604. te[ 2 ] = ( xz - wy ) * sx;
  9605. te[ 3 ] = 0;
  9606. te[ 4 ] = ( xy - wz ) * sy;
  9607. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9608. te[ 6 ] = ( yz + wx ) * sy;
  9609. te[ 7 ] = 0;
  9610. te[ 8 ] = ( xz + wy ) * sz;
  9611. te[ 9 ] = ( yz - wx ) * sz;
  9612. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9613. te[ 11 ] = 0;
  9614. te[ 12 ] = position.x;
  9615. te[ 13 ] = position.y;
  9616. te[ 14 ] = position.z;
  9617. te[ 15 ] = 1;
  9618. return this;
  9619. }
  9620. /**
  9621. * Decomposes this matrix into its position, rotation and scale components
  9622. * and provides the result in the given objects.
  9623. *
  9624. * Note: Not all matrices are decomposable in this way. For example, if an
  9625. * object has a non-uniformly scaled parent, then the object's world matrix
  9626. * may not be decomposable, and this method may not be appropriate.
  9627. *
  9628. * @param {Vector3} position - The position vector.
  9629. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9630. * @param {Vector3} scale - The scale vector.
  9631. * @return {Matrix4} A reference to this matrix.
  9632. */
  9633. decompose( position, quaternion, scale ) {
  9634. const te = this.elements;
  9635. position.x = te[ 12 ];
  9636. position.y = te[ 13 ];
  9637. position.z = te[ 14 ];
  9638. const det = this.determinant();
  9639. if ( det === 0 ) {
  9640. scale.set( 1, 1, 1 );
  9641. quaternion.identity();
  9642. return this;
  9643. }
  9644. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9645. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9646. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9647. // if determinant is negative, we need to invert one scale
  9648. if ( det < 0 ) sx = - sx;
  9649. // scale the rotation part
  9650. _m1$2.copy( this );
  9651. const invSX = 1 / sx;
  9652. const invSY = 1 / sy;
  9653. const invSZ = 1 / sz;
  9654. _m1$2.elements[ 0 ] *= invSX;
  9655. _m1$2.elements[ 1 ] *= invSX;
  9656. _m1$2.elements[ 2 ] *= invSX;
  9657. _m1$2.elements[ 4 ] *= invSY;
  9658. _m1$2.elements[ 5 ] *= invSY;
  9659. _m1$2.elements[ 6 ] *= invSY;
  9660. _m1$2.elements[ 8 ] *= invSZ;
  9661. _m1$2.elements[ 9 ] *= invSZ;
  9662. _m1$2.elements[ 10 ] *= invSZ;
  9663. quaternion.setFromRotationMatrix( _m1$2 );
  9664. scale.x = sx;
  9665. scale.y = sy;
  9666. scale.z = sz;
  9667. return this;
  9668. }
  9669. /**
  9670. * Creates a perspective projection matrix. This is used internally by
  9671. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9672. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9673. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9674. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9675. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9676. * @param {number} near - The distance from the camera to the near plane.
  9677. * @param {number} far - The distance from the camera to the far plane.
  9678. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9679. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9680. * @return {Matrix4} A reference to this matrix.
  9681. */
  9682. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9683. const te = this.elements;
  9684. const x = 2 * near / ( right - left );
  9685. const y = 2 * near / ( top - bottom );
  9686. const a = ( right + left ) / ( right - left );
  9687. const b = ( top + bottom ) / ( top - bottom );
  9688. let c, d;
  9689. if ( reversedDepth ) {
  9690. c = near / ( far - near );
  9691. d = ( far * near ) / ( far - near );
  9692. } else {
  9693. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9694. c = - ( far + near ) / ( far - near );
  9695. d = ( -2 * far * near ) / ( far - near );
  9696. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9697. c = - far / ( far - near );
  9698. d = ( - far * near ) / ( far - near );
  9699. } else {
  9700. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9701. }
  9702. }
  9703. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9704. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9705. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9706. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9707. return this;
  9708. }
  9709. /**
  9710. * Creates a orthographic projection matrix. This is used internally by
  9711. * {@link OrthographicCamera#updateProjectionMatrix}.
  9712. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9713. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9714. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9715. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9716. * @param {number} near - The distance from the camera to the near plane.
  9717. * @param {number} far - The distance from the camera to the far plane.
  9718. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9719. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9720. * @return {Matrix4} A reference to this matrix.
  9721. */
  9722. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9723. const te = this.elements;
  9724. const x = 2 / ( right - left );
  9725. const y = 2 / ( top - bottom );
  9726. const a = - ( right + left ) / ( right - left );
  9727. const b = - ( top + bottom ) / ( top - bottom );
  9728. let c, d;
  9729. if ( reversedDepth ) {
  9730. c = 1 / ( far - near );
  9731. d = far / ( far - near );
  9732. } else {
  9733. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9734. c = -2 / ( far - near );
  9735. d = - ( far + near ) / ( far - near );
  9736. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9737. c = -1 / ( far - near );
  9738. d = - near / ( far - near );
  9739. } else {
  9740. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9741. }
  9742. }
  9743. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9744. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9745. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9746. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9747. return this;
  9748. }
  9749. /**
  9750. * Returns `true` if this matrix is equal with the given one.
  9751. *
  9752. * @param {Matrix4} matrix - The matrix to test for equality.
  9753. * @return {boolean} Whether this matrix is equal with the given one.
  9754. */
  9755. equals( matrix ) {
  9756. const te = this.elements;
  9757. const me = matrix.elements;
  9758. for ( let i = 0; i < 16; i ++ ) {
  9759. if ( te[ i ] !== me[ i ] ) return false;
  9760. }
  9761. return true;
  9762. }
  9763. /**
  9764. * Sets the elements of the matrix from the given array.
  9765. *
  9766. * @param {Array<number>} array - The matrix elements in column-major order.
  9767. * @param {number} [offset=0] - Index of the first element in the array.
  9768. * @return {Matrix4} A reference to this matrix.
  9769. */
  9770. fromArray( array, offset = 0 ) {
  9771. for ( let i = 0; i < 16; i ++ ) {
  9772. this.elements[ i ] = array[ i + offset ];
  9773. }
  9774. return this;
  9775. }
  9776. /**
  9777. * Writes the elements of this matrix to the given array. If no array is provided,
  9778. * the method returns a new instance.
  9779. *
  9780. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9781. * @param {number} [offset=0] - Index of the first element in the array.
  9782. * @return {Array<number>} The matrix elements in column-major order.
  9783. */
  9784. toArray( array = [], offset = 0 ) {
  9785. const te = this.elements;
  9786. array[ offset ] = te[ 0 ];
  9787. array[ offset + 1 ] = te[ 1 ];
  9788. array[ offset + 2 ] = te[ 2 ];
  9789. array[ offset + 3 ] = te[ 3 ];
  9790. array[ offset + 4 ] = te[ 4 ];
  9791. array[ offset + 5 ] = te[ 5 ];
  9792. array[ offset + 6 ] = te[ 6 ];
  9793. array[ offset + 7 ] = te[ 7 ];
  9794. array[ offset + 8 ] = te[ 8 ];
  9795. array[ offset + 9 ] = te[ 9 ];
  9796. array[ offset + 10 ] = te[ 10 ];
  9797. array[ offset + 11 ] = te[ 11 ];
  9798. array[ offset + 12 ] = te[ 12 ];
  9799. array[ offset + 13 ] = te[ 13 ];
  9800. array[ offset + 14 ] = te[ 14 ];
  9801. array[ offset + 15 ] = te[ 15 ];
  9802. return array;
  9803. }
  9804. }
  9805. const _v1$5 = /*@__PURE__*/ new Vector3();
  9806. const _m1$2 = /*@__PURE__*/ new Matrix4();
  9807. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9808. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9809. const _x = /*@__PURE__*/ new Vector3();
  9810. const _y = /*@__PURE__*/ new Vector3();
  9811. const _z = /*@__PURE__*/ new Vector3();
  9812. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9813. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  9814. /**
  9815. * A class representing Euler angles.
  9816. *
  9817. * Euler angles describe a rotational transformation by rotating an object on
  9818. * its various axes in specified amounts per axis, and a specified axis
  9819. * order.
  9820. *
  9821. * Iterating through an instance will yield its components (x, y, z,
  9822. * order) in the corresponding order.
  9823. *
  9824. * ```js
  9825. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9826. * const b = new THREE.Vector3( 1, 0, 1 );
  9827. * b.applyEuler(a);
  9828. * ```
  9829. */
  9830. class Euler {
  9831. /**
  9832. * Constructs a new euler instance.
  9833. *
  9834. * @param {number} [x=0] - The angle of the x axis in radians.
  9835. * @param {number} [y=0] - The angle of the y axis in radians.
  9836. * @param {number} [z=0] - The angle of the z axis in radians.
  9837. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9838. */
  9839. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9840. /**
  9841. * This flag can be used for type testing.
  9842. *
  9843. * @type {boolean}
  9844. * @readonly
  9845. * @default true
  9846. */
  9847. this.isEuler = true;
  9848. this._x = x;
  9849. this._y = y;
  9850. this._z = z;
  9851. this._order = order;
  9852. }
  9853. /**
  9854. * The angle of the x axis in radians.
  9855. *
  9856. * @type {number}
  9857. * @default 0
  9858. */
  9859. get x() {
  9860. return this._x;
  9861. }
  9862. set x( value ) {
  9863. this._x = value;
  9864. this._onChangeCallback();
  9865. }
  9866. /**
  9867. * The angle of the y axis in radians.
  9868. *
  9869. * @type {number}
  9870. * @default 0
  9871. */
  9872. get y() {
  9873. return this._y;
  9874. }
  9875. set y( value ) {
  9876. this._y = value;
  9877. this._onChangeCallback();
  9878. }
  9879. /**
  9880. * The angle of the z axis in radians.
  9881. *
  9882. * @type {number}
  9883. * @default 0
  9884. */
  9885. get z() {
  9886. return this._z;
  9887. }
  9888. set z( value ) {
  9889. this._z = value;
  9890. this._onChangeCallback();
  9891. }
  9892. /**
  9893. * A string representing the order that the rotations are applied.
  9894. *
  9895. * @type {string}
  9896. * @default 'XYZ'
  9897. */
  9898. get order() {
  9899. return this._order;
  9900. }
  9901. set order( value ) {
  9902. this._order = value;
  9903. this._onChangeCallback();
  9904. }
  9905. /**
  9906. * Sets the Euler components.
  9907. *
  9908. * @param {number} x - The angle of the x axis in radians.
  9909. * @param {number} y - The angle of the y axis in radians.
  9910. * @param {number} z - The angle of the z axis in radians.
  9911. * @param {string} [order] - A string representing the order that the rotations are applied.
  9912. * @return {Euler} A reference to this Euler instance.
  9913. */
  9914. set( x, y, z, order = this._order ) {
  9915. this._x = x;
  9916. this._y = y;
  9917. this._z = z;
  9918. this._order = order;
  9919. this._onChangeCallback();
  9920. return this;
  9921. }
  9922. /**
  9923. * Returns a new Euler instance with copied values from this instance.
  9924. *
  9925. * @return {Euler} A clone of this instance.
  9926. */
  9927. clone() {
  9928. return new this.constructor( this._x, this._y, this._z, this._order );
  9929. }
  9930. /**
  9931. * Copies the values of the given Euler instance to this instance.
  9932. *
  9933. * @param {Euler} euler - The Euler instance to copy.
  9934. * @return {Euler} A reference to this Euler instance.
  9935. */
  9936. copy( euler ) {
  9937. this._x = euler._x;
  9938. this._y = euler._y;
  9939. this._z = euler._z;
  9940. this._order = euler._order;
  9941. this._onChangeCallback();
  9942. return this;
  9943. }
  9944. /**
  9945. * Sets the angles of this Euler instance from a pure rotation matrix.
  9946. *
  9947. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9948. * @param {string} [order] - A string representing the order that the rotations are applied.
  9949. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9950. * @return {Euler} A reference to this Euler instance.
  9951. */
  9952. setFromRotationMatrix( m, order = this._order, update = true ) {
  9953. const te = m.elements;
  9954. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9955. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9956. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9957. switch ( order ) {
  9958. case 'XYZ':
  9959. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9960. if ( Math.abs( m13 ) < 0.9999999 ) {
  9961. this._x = Math.atan2( - m23, m33 );
  9962. this._z = Math.atan2( - m12, m11 );
  9963. } else {
  9964. this._x = Math.atan2( m32, m22 );
  9965. this._z = 0;
  9966. }
  9967. break;
  9968. case 'YXZ':
  9969. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9970. if ( Math.abs( m23 ) < 0.9999999 ) {
  9971. this._y = Math.atan2( m13, m33 );
  9972. this._z = Math.atan2( m21, m22 );
  9973. } else {
  9974. this._y = Math.atan2( - m31, m11 );
  9975. this._z = 0;
  9976. }
  9977. break;
  9978. case 'ZXY':
  9979. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9980. if ( Math.abs( m32 ) < 0.9999999 ) {
  9981. this._y = Math.atan2( - m31, m33 );
  9982. this._z = Math.atan2( - m12, m22 );
  9983. } else {
  9984. this._y = 0;
  9985. this._z = Math.atan2( m21, m11 );
  9986. }
  9987. break;
  9988. case 'ZYX':
  9989. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9990. if ( Math.abs( m31 ) < 0.9999999 ) {
  9991. this._x = Math.atan2( m32, m33 );
  9992. this._z = Math.atan2( m21, m11 );
  9993. } else {
  9994. this._x = 0;
  9995. this._z = Math.atan2( - m12, m22 );
  9996. }
  9997. break;
  9998. case 'YZX':
  9999. this._z = Math.asin( clamp( m21, -1, 1 ) );
  10000. if ( Math.abs( m21 ) < 0.9999999 ) {
  10001. this._x = Math.atan2( - m23, m22 );
  10002. this._y = Math.atan2( - m31, m11 );
  10003. } else {
  10004. this._x = 0;
  10005. this._y = Math.atan2( m13, m33 );
  10006. }
  10007. break;
  10008. case 'XZY':
  10009. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  10010. if ( Math.abs( m12 ) < 0.9999999 ) {
  10011. this._x = Math.atan2( m32, m22 );
  10012. this._y = Math.atan2( m13, m11 );
  10013. } else {
  10014. this._x = Math.atan2( - m23, m33 );
  10015. this._y = 0;
  10016. }
  10017. break;
  10018. default:
  10019. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  10020. }
  10021. this._order = order;
  10022. if ( update === true ) this._onChangeCallback();
  10023. return this;
  10024. }
  10025. /**
  10026. * Sets the angles of this Euler instance from a normalized quaternion.
  10027. *
  10028. * @param {Quaternion} q - A normalized Quaternion.
  10029. * @param {string} [order] - A string representing the order that the rotations are applied.
  10030. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  10031. * @return {Euler} A reference to this Euler instance.
  10032. */
  10033. setFromQuaternion( q, order, update ) {
  10034. _matrix$2.makeRotationFromQuaternion( q );
  10035. return this.setFromRotationMatrix( _matrix$2, order, update );
  10036. }
  10037. /**
  10038. * Sets the angles of this Euler instance from the given vector.
  10039. *
  10040. * @param {Vector3} v - The vector.
  10041. * @param {string} [order] - A string representing the order that the rotations are applied.
  10042. * @return {Euler} A reference to this Euler instance.
  10043. */
  10044. setFromVector3( v, order = this._order ) {
  10045. return this.set( v.x, v.y, v.z, order );
  10046. }
  10047. /**
  10048. * Resets the euler angle with a new order by creating a quaternion from this
  10049. * euler angle and then setting this euler angle with the quaternion and the
  10050. * new order.
  10051. *
  10052. * Warning: This discards revolution information.
  10053. *
  10054. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  10055. * @return {Euler} A reference to this Euler instance.
  10056. */
  10057. reorder( newOrder ) {
  10058. _quaternion$4.setFromEuler( this );
  10059. return this.setFromQuaternion( _quaternion$4, newOrder );
  10060. }
  10061. /**
  10062. * Returns `true` if this Euler instance is equal with the given one.
  10063. *
  10064. * @param {Euler} euler - The Euler instance to test for equality.
  10065. * @return {boolean} Whether this Euler instance is equal with the given one.
  10066. */
  10067. equals( euler ) {
  10068. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  10069. }
  10070. /**
  10071. * Sets this Euler instance's components to values from the given array. The first three
  10072. * entries of the array are assign to the x,y and z components. An optional fourth entry
  10073. * defines the Euler order.
  10074. *
  10075. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  10076. * @return {Euler} A reference to this Euler instance.
  10077. */
  10078. fromArray( array ) {
  10079. this._x = array[ 0 ];
  10080. this._y = array[ 1 ];
  10081. this._z = array[ 2 ];
  10082. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  10083. this._onChangeCallback();
  10084. return this;
  10085. }
  10086. /**
  10087. * Writes the components of this Euler instance to the given array. If no array is provided,
  10088. * the method returns a new instance.
  10089. *
  10090. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  10091. * @param {number} [offset=0] - Index of the first element in the array.
  10092. * @return {Array<number,number,number,string>} The Euler components.
  10093. */
  10094. toArray( array = [], offset = 0 ) {
  10095. array[ offset ] = this._x;
  10096. array[ offset + 1 ] = this._y;
  10097. array[ offset + 2 ] = this._z;
  10098. array[ offset + 3 ] = this._order;
  10099. return array;
  10100. }
  10101. _onChange( callback ) {
  10102. this._onChangeCallback = callback;
  10103. return this;
  10104. }
  10105. _onChangeCallback() {}
  10106. *[ Symbol.iterator ]() {
  10107. yield this._x;
  10108. yield this._y;
  10109. yield this._z;
  10110. yield this._order;
  10111. }
  10112. }
  10113. /**
  10114. * The default Euler angle order.
  10115. *
  10116. * @static
  10117. * @type {string}
  10118. * @default 'XYZ'
  10119. */
  10120. Euler.DEFAULT_ORDER = 'XYZ';
  10121. /**
  10122. * A layers object assigns an 3D object to 1 or more of 32
  10123. * layers numbered `0` to `31` - internally the layers are stored as a
  10124. * bit mask], and by default all 3D objects are a member of layer `0`.
  10125. *
  10126. * This can be used to control visibility - an object must share a layer with
  10127. * a camera to be visible when that camera's view is
  10128. * rendered.
  10129. *
  10130. * All classes that inherit from {@link Object3D} have an `layers` property which
  10131. * is an instance of this class.
  10132. */
  10133. class Layers {
  10134. /**
  10135. * Constructs a new layers instance, with membership
  10136. * initially set to layer `0`.
  10137. */
  10138. constructor() {
  10139. /**
  10140. * A bit mask storing which of the 32 layers this layers object is currently
  10141. * a member of.
  10142. *
  10143. * @type {number}
  10144. */
  10145. this.mask = 1 | 0;
  10146. }
  10147. /**
  10148. * Sets membership to the given layer, and remove membership all other layers.
  10149. *
  10150. * @param {number} layer - The layer to set.
  10151. */
  10152. set( layer ) {
  10153. this.mask = ( 1 << layer | 0 ) >>> 0;
  10154. }
  10155. /**
  10156. * Adds membership of the given layer.
  10157. *
  10158. * @param {number} layer - The layer to enable.
  10159. */
  10160. enable( layer ) {
  10161. this.mask |= 1 << layer | 0;
  10162. }
  10163. /**
  10164. * Adds membership to all layers.
  10165. */
  10166. enableAll() {
  10167. this.mask = 0xffffffff | 0;
  10168. }
  10169. /**
  10170. * Toggles the membership of the given layer.
  10171. *
  10172. * @param {number} layer - The layer to toggle.
  10173. */
  10174. toggle( layer ) {
  10175. this.mask ^= 1 << layer | 0;
  10176. }
  10177. /**
  10178. * Removes membership of the given layer.
  10179. *
  10180. * @param {number} layer - The layer to enable.
  10181. */
  10182. disable( layer ) {
  10183. this.mask &= ~ ( 1 << layer | 0 );
  10184. }
  10185. /**
  10186. * Removes the membership from all layers.
  10187. */
  10188. disableAll() {
  10189. this.mask = 0;
  10190. }
  10191. /**
  10192. * Returns `true` if this and the given layers object have at least one
  10193. * layer in common.
  10194. *
  10195. * @param {Layers} layers - The layers to test.
  10196. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  10197. */
  10198. test( layers ) {
  10199. return ( this.mask & layers.mask ) !== 0;
  10200. }
  10201. /**
  10202. * Returns `true` if the given layer is enabled.
  10203. *
  10204. * @param {number} layer - The layer to test.
  10205. * @return {boolean } Whether the given layer is enabled or not.
  10206. */
  10207. isEnabled( layer ) {
  10208. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  10209. }
  10210. }
  10211. let _object3DId = 0;
  10212. const _v1$4 = /*@__PURE__*/ new Vector3();
  10213. const _q1 = /*@__PURE__*/ new Quaternion();
  10214. const _m1$1 = /*@__PURE__*/ new Matrix4();
  10215. const _target = /*@__PURE__*/ new Vector3();
  10216. const _position$4 = /*@__PURE__*/ new Vector3();
  10217. const _scale$3 = /*@__PURE__*/ new Vector3();
  10218. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  10219. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  10220. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10221. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  10222. /**
  10223. * Fires when the object has been added to its parent object.
  10224. *
  10225. * @event Object3D#added
  10226. * @type {Object}
  10227. */
  10228. const _addedEvent = { type: 'added' };
  10229. /**
  10230. * Fires when the object has been removed from its parent object.
  10231. *
  10232. * @event Object3D#removed
  10233. * @type {Object}
  10234. */
  10235. const _removedEvent = { type: 'removed' };
  10236. /**
  10237. * Fires when a new child object has been added.
  10238. *
  10239. * @event Object3D#childadded
  10240. * @type {Object}
  10241. */
  10242. const _childaddedEvent = { type: 'childadded', child: null };
  10243. /**
  10244. * Fires when a child object has been removed.
  10245. *
  10246. * @event Object3D#childremoved
  10247. * @type {Object}
  10248. */
  10249. const _childremovedEvent = { type: 'childremoved', child: null };
  10250. /**
  10251. * This is the base class for most objects in three.js and provides a set of
  10252. * properties and methods for manipulating objects in 3D space.
  10253. *
  10254. * @augments EventDispatcher
  10255. */
  10256. class Object3D extends EventDispatcher {
  10257. /**
  10258. * Constructs a new 3D object.
  10259. */
  10260. constructor() {
  10261. super();
  10262. /**
  10263. * This flag can be used for type testing.
  10264. *
  10265. * @type {boolean}
  10266. * @readonly
  10267. * @default true
  10268. */
  10269. this.isObject3D = true;
  10270. /**
  10271. * The ID of the 3D object.
  10272. *
  10273. * @name Object3D#id
  10274. * @type {number}
  10275. * @readonly
  10276. */
  10277. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10278. /**
  10279. * The UUID of the 3D object.
  10280. *
  10281. * @type {string}
  10282. * @readonly
  10283. */
  10284. this.uuid = generateUUID();
  10285. /**
  10286. * The name of the 3D object.
  10287. *
  10288. * @type {string}
  10289. */
  10290. this.name = '';
  10291. /**
  10292. * The type property is used for detecting the object type
  10293. * in context of serialization/deserialization.
  10294. *
  10295. * @type {string}
  10296. * @readonly
  10297. */
  10298. this.type = 'Object3D';
  10299. /**
  10300. * A reference to the parent object.
  10301. *
  10302. * @type {?Object3D}
  10303. * @default null
  10304. */
  10305. this.parent = null;
  10306. /**
  10307. * An array holding the child 3D objects of this instance.
  10308. *
  10309. * @type {Array<Object3D>}
  10310. */
  10311. this.children = [];
  10312. /**
  10313. * Defines the `up` direction of the 3D object which influences
  10314. * the orientation via methods like {@link Object3D#lookAt}.
  10315. *
  10316. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10317. *
  10318. * @type {Vector3}
  10319. */
  10320. this.up = Object3D.DEFAULT_UP.clone();
  10321. const position = new Vector3();
  10322. const rotation = new Euler();
  10323. const quaternion = new Quaternion();
  10324. const scale = new Vector3( 1, 1, 1 );
  10325. function onRotationChange() {
  10326. quaternion.setFromEuler( rotation, false );
  10327. }
  10328. function onQuaternionChange() {
  10329. rotation.setFromQuaternion( quaternion, undefined, false );
  10330. }
  10331. rotation._onChange( onRotationChange );
  10332. quaternion._onChange( onQuaternionChange );
  10333. Object.defineProperties( this, {
  10334. /**
  10335. * Represents the object's local position.
  10336. *
  10337. * @name Object3D#position
  10338. * @type {Vector3}
  10339. * @default (0,0,0)
  10340. */
  10341. position: {
  10342. configurable: true,
  10343. enumerable: true,
  10344. value: position
  10345. },
  10346. /**
  10347. * Represents the object's local rotation as Euler angles, in radians.
  10348. *
  10349. * @name Object3D#rotation
  10350. * @type {Euler}
  10351. * @default (0,0,0)
  10352. */
  10353. rotation: {
  10354. configurable: true,
  10355. enumerable: true,
  10356. value: rotation
  10357. },
  10358. /**
  10359. * Represents the object's local rotation as Quaternions.
  10360. *
  10361. * @name Object3D#quaternion
  10362. * @type {Quaternion}
  10363. */
  10364. quaternion: {
  10365. configurable: true,
  10366. enumerable: true,
  10367. value: quaternion
  10368. },
  10369. /**
  10370. * Represents the object's local scale.
  10371. *
  10372. * @name Object3D#scale
  10373. * @type {Vector3}
  10374. * @default (1,1,1)
  10375. */
  10376. scale: {
  10377. configurable: true,
  10378. enumerable: true,
  10379. value: scale
  10380. },
  10381. /**
  10382. * Represents the object's model-view matrix.
  10383. *
  10384. * @name Object3D#modelViewMatrix
  10385. * @type {Matrix4}
  10386. */
  10387. modelViewMatrix: {
  10388. value: new Matrix4()
  10389. },
  10390. /**
  10391. * Represents the object's normal matrix.
  10392. *
  10393. * @name Object3D#normalMatrix
  10394. * @type {Matrix3}
  10395. */
  10396. normalMatrix: {
  10397. value: new Matrix3()
  10398. }
  10399. } );
  10400. /**
  10401. * Represents the object's transformation matrix in local space.
  10402. *
  10403. * @type {Matrix4}
  10404. */
  10405. this.matrix = new Matrix4();
  10406. /**
  10407. * Represents the object's transformation matrix in world space.
  10408. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10409. *
  10410. * @type {Matrix4}
  10411. */
  10412. this.matrixWorld = new Matrix4();
  10413. /**
  10414. * When set to `true`, the engine automatically computes the local matrix from position,
  10415. * rotation and scale every frame.
  10416. *
  10417. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10418. *
  10419. * @type {boolean}
  10420. * @default true
  10421. */
  10422. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10423. /**
  10424. * When set to `true`, the engine automatically computes the world matrix from the current local
  10425. * matrix and the object's transformation hierarchy.
  10426. *
  10427. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10428. *
  10429. * @type {boolean}
  10430. * @default true
  10431. */
  10432. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10433. /**
  10434. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10435. * to `false`.
  10436. *
  10437. * @type {boolean}
  10438. * @default false
  10439. */
  10440. this.matrixWorldNeedsUpdate = false;
  10441. /**
  10442. * The layer membership of the 3D object. The 3D object is only visible if it has
  10443. * at least one layer in common with the camera in use. This property can also be
  10444. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10445. *
  10446. * @type {Layers}
  10447. */
  10448. this.layers = new Layers();
  10449. /**
  10450. * When set to `true`, the 3D object gets rendered.
  10451. *
  10452. * @type {boolean}
  10453. * @default true
  10454. */
  10455. this.visible = true;
  10456. /**
  10457. * When set to `true`, the 3D object gets rendered into shadow maps.
  10458. *
  10459. * @type {boolean}
  10460. * @default false
  10461. */
  10462. this.castShadow = false;
  10463. /**
  10464. * When set to `true`, the 3D object is affected by shadows in the scene.
  10465. *
  10466. * @type {boolean}
  10467. * @default false
  10468. */
  10469. this.receiveShadow = false;
  10470. /**
  10471. * When set to `true`, the 3D object is honored by view frustum culling.
  10472. *
  10473. * @type {boolean}
  10474. * @default true
  10475. */
  10476. this.frustumCulled = true;
  10477. /**
  10478. * This value allows the default rendering order of scene graph objects to be
  10479. * overridden although opaque and transparent objects remain sorted independently.
  10480. * When this property is set for an instance of {@link Group},all descendants
  10481. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10482. * render order.
  10483. *
  10484. * @type {number}
  10485. * @default 0
  10486. */
  10487. this.renderOrder = 0;
  10488. /**
  10489. * An array holding the animation clips of the 3D object.
  10490. *
  10491. * @type {Array<AnimationClip>}
  10492. */
  10493. this.animations = [];
  10494. /**
  10495. * Custom depth material to be used when rendering to the depth map. Can only be used
  10496. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10497. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10498. * material for proper shadows.
  10499. *
  10500. * Only relevant in context of {@link WebGLRenderer}.
  10501. *
  10502. * @type {(Material|undefined)}
  10503. * @default undefined
  10504. */
  10505. this.customDepthMaterial = undefined;
  10506. /**
  10507. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10508. *
  10509. * Only relevant in context of {@link WebGLRenderer}.
  10510. *
  10511. * @type {(Material|undefined)}
  10512. * @default undefined
  10513. */
  10514. this.customDistanceMaterial = undefined;
  10515. /**
  10516. * Whether the 3D object is supposed to be static or not. If set to `true`, it means
  10517. * the 3D object is not going to be changed after the initial renderer. This includes
  10518. * geometry and material settings. A static 3D object can be processed by the renderer
  10519. * slightly faster since certain state checks can be bypassed.
  10520. *
  10521. * Only relevant in context of {@link WebGPURenderer}.
  10522. *
  10523. * @type {boolean}
  10524. * @default false
  10525. */
  10526. this.static = false;
  10527. /**
  10528. * An object that can be used to store custom data about the 3D object. It
  10529. * should not hold references to functions as these will not be cloned.
  10530. *
  10531. * @type {Object}
  10532. */
  10533. this.userData = {};
  10534. /**
  10535. * The pivot point for rotation and scale transformations.
  10536. * When set, rotation and scale are applied around this point
  10537. * instead of the object's origin.
  10538. *
  10539. * @type {?Vector3}
  10540. * @default null
  10541. */
  10542. this.pivot = null;
  10543. }
  10544. /**
  10545. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10546. *
  10547. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10548. * @param {Object3D} object - The 3D object.
  10549. * @param {Camera} camera - The camera that is used to render the scene.
  10550. * @param {Camera} shadowCamera - The shadow camera.
  10551. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10552. * @param {Material} depthMaterial - The depth material.
  10553. * @param {Object} group - The geometry group data.
  10554. */
  10555. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10556. /**
  10557. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10558. *
  10559. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10560. * @param {Object3D} object - The 3D object.
  10561. * @param {Camera} camera - The camera that is used to render the scene.
  10562. * @param {Camera} shadowCamera - The shadow camera.
  10563. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10564. * @param {Material} depthMaterial - The depth material.
  10565. * @param {Object} group - The geometry group data.
  10566. */
  10567. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10568. /**
  10569. * A callback that is executed immediately before a 3D object is rendered.
  10570. *
  10571. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10572. * @param {Object3D} object - The 3D object.
  10573. * @param {Camera} camera - The camera that is used to render the scene.
  10574. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10575. * @param {Material} material - The 3D object's material.
  10576. * @param {Object} group - The geometry group data.
  10577. */
  10578. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10579. /**
  10580. * A callback that is executed immediately after a 3D object is rendered.
  10581. *
  10582. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10583. * @param {Object3D} object - The 3D object.
  10584. * @param {Camera} camera - The camera that is used to render the scene.
  10585. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10586. * @param {Material} material - The 3D object's material.
  10587. * @param {Object} group - The geometry group data.
  10588. */
  10589. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10590. /**
  10591. * Applies the given transformation matrix to the object and updates the object's position,
  10592. * rotation and scale.
  10593. *
  10594. * @param {Matrix4} matrix - The transformation matrix.
  10595. */
  10596. applyMatrix4( matrix ) {
  10597. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10598. this.matrix.premultiply( matrix );
  10599. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10600. }
  10601. /**
  10602. * Applies a rotation represented by given the quaternion to the 3D object.
  10603. *
  10604. * @param {Quaternion} q - The quaternion.
  10605. * @return {Object3D} A reference to this instance.
  10606. */
  10607. applyQuaternion( q ) {
  10608. this.quaternion.premultiply( q );
  10609. return this;
  10610. }
  10611. /**
  10612. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10613. *
  10614. * @param {Vector3} axis - The (normalized) axis vector.
  10615. * @param {number} angle - The angle in radians.
  10616. */
  10617. setRotationFromAxisAngle( axis, angle ) {
  10618. // assumes axis is normalized
  10619. this.quaternion.setFromAxisAngle( axis, angle );
  10620. }
  10621. /**
  10622. * Sets the given rotation represented as Euler angles to the 3D object.
  10623. *
  10624. * @param {Euler} euler - The Euler angles.
  10625. */
  10626. setRotationFromEuler( euler ) {
  10627. this.quaternion.setFromEuler( euler, true );
  10628. }
  10629. /**
  10630. * Sets the given rotation represented as rotation matrix to the 3D object.
  10631. *
  10632. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10633. * a pure rotation matrix (i.e, unscaled).
  10634. */
  10635. setRotationFromMatrix( m ) {
  10636. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10637. this.quaternion.setFromRotationMatrix( m );
  10638. }
  10639. /**
  10640. * Sets the given rotation represented as a Quaternion to the 3D object.
  10641. *
  10642. * @param {Quaternion} q - The Quaternion
  10643. */
  10644. setRotationFromQuaternion( q ) {
  10645. // assumes q is normalized
  10646. this.quaternion.copy( q );
  10647. }
  10648. /**
  10649. * Rotates the 3D object along an axis in local space.
  10650. *
  10651. * @param {Vector3} axis - The (normalized) axis vector.
  10652. * @param {number} angle - The angle in radians.
  10653. * @return {Object3D} A reference to this instance.
  10654. */
  10655. rotateOnAxis( axis, angle ) {
  10656. // rotate object on axis in object space
  10657. // axis is assumed to be normalized
  10658. _q1.setFromAxisAngle( axis, angle );
  10659. this.quaternion.multiply( _q1 );
  10660. return this;
  10661. }
  10662. /**
  10663. * Rotates the 3D object along an axis in world space.
  10664. *
  10665. * @param {Vector3} axis - The (normalized) axis vector.
  10666. * @param {number} angle - The angle in radians.
  10667. * @return {Object3D} A reference to this instance.
  10668. */
  10669. rotateOnWorldAxis( axis, angle ) {
  10670. // rotate object on axis in world space
  10671. // axis is assumed to be normalized
  10672. // method assumes no rotated parent
  10673. _q1.setFromAxisAngle( axis, angle );
  10674. this.quaternion.premultiply( _q1 );
  10675. return this;
  10676. }
  10677. /**
  10678. * Rotates the 3D object around its X axis in local space.
  10679. *
  10680. * @param {number} angle - The angle in radians.
  10681. * @return {Object3D} A reference to this instance.
  10682. */
  10683. rotateX( angle ) {
  10684. return this.rotateOnAxis( _xAxis, angle );
  10685. }
  10686. /**
  10687. * Rotates the 3D object around its Y axis in local space.
  10688. *
  10689. * @param {number} angle - The angle in radians.
  10690. * @return {Object3D} A reference to this instance.
  10691. */
  10692. rotateY( angle ) {
  10693. return this.rotateOnAxis( _yAxis, angle );
  10694. }
  10695. /**
  10696. * Rotates the 3D object around its Z axis in local space.
  10697. *
  10698. * @param {number} angle - The angle in radians.
  10699. * @return {Object3D} A reference to this instance.
  10700. */
  10701. rotateZ( angle ) {
  10702. return this.rotateOnAxis( _zAxis, angle );
  10703. }
  10704. /**
  10705. * Translate the 3D object by a distance along the given axis in local space.
  10706. *
  10707. * @param {Vector3} axis - The (normalized) axis vector.
  10708. * @param {number} distance - The distance in world units.
  10709. * @return {Object3D} A reference to this instance.
  10710. */
  10711. translateOnAxis( axis, distance ) {
  10712. // translate object by distance along axis in object space
  10713. // axis is assumed to be normalized
  10714. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10715. this.position.add( _v1$4.multiplyScalar( distance ) );
  10716. return this;
  10717. }
  10718. /**
  10719. * Translate the 3D object by a distance along its X-axis in local space.
  10720. *
  10721. * @param {number} distance - The distance in world units.
  10722. * @return {Object3D} A reference to this instance.
  10723. */
  10724. translateX( distance ) {
  10725. return this.translateOnAxis( _xAxis, distance );
  10726. }
  10727. /**
  10728. * Translate the 3D object by a distance along its Y-axis in local space.
  10729. *
  10730. * @param {number} distance - The distance in world units.
  10731. * @return {Object3D} A reference to this instance.
  10732. */
  10733. translateY( distance ) {
  10734. return this.translateOnAxis( _yAxis, distance );
  10735. }
  10736. /**
  10737. * Translate the 3D object by a distance along its Z-axis in local space.
  10738. *
  10739. * @param {number} distance - The distance in world units.
  10740. * @return {Object3D} A reference to this instance.
  10741. */
  10742. translateZ( distance ) {
  10743. return this.translateOnAxis( _zAxis, distance );
  10744. }
  10745. /**
  10746. * Converts the given vector from this 3D object's local space to world space.
  10747. *
  10748. * @param {Vector3} vector - The vector to convert.
  10749. * @return {Vector3} The converted vector.
  10750. */
  10751. localToWorld( vector ) {
  10752. this.updateWorldMatrix( true, false );
  10753. return vector.applyMatrix4( this.matrixWorld );
  10754. }
  10755. /**
  10756. * Converts the given vector from this 3D object's world space to local space.
  10757. *
  10758. * @param {Vector3} vector - The vector to convert.
  10759. * @return {Vector3} The converted vector.
  10760. */
  10761. worldToLocal( vector ) {
  10762. this.updateWorldMatrix( true, false );
  10763. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  10764. }
  10765. /**
  10766. * Rotates the object to face a point in world space.
  10767. *
  10768. * This method does not support objects having non-uniformly-scaled parent(s).
  10769. *
  10770. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10771. * @param {number} [y] - The y coordinate in world space.
  10772. * @param {number} [z] - The z coordinate in world space.
  10773. */
  10774. lookAt( x, y, z ) {
  10775. // This method does not support objects having non-uniformly-scaled parent(s)
  10776. if ( x.isVector3 ) {
  10777. _target.copy( x );
  10778. } else {
  10779. _target.set( x, y, z );
  10780. }
  10781. const parent = this.parent;
  10782. this.updateWorldMatrix( true, false );
  10783. _position$4.setFromMatrixPosition( this.matrixWorld );
  10784. if ( this.isCamera || this.isLight ) {
  10785. _m1$1.lookAt( _position$4, _target, this.up );
  10786. } else {
  10787. _m1$1.lookAt( _target, _position$4, this.up );
  10788. }
  10789. this.quaternion.setFromRotationMatrix( _m1$1 );
  10790. if ( parent ) {
  10791. _m1$1.extractRotation( parent.matrixWorld );
  10792. _q1.setFromRotationMatrix( _m1$1 );
  10793. this.quaternion.premultiply( _q1.invert() );
  10794. }
  10795. }
  10796. /**
  10797. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10798. * objects may be added. Any current parent on an object passed in here will be
  10799. * removed, since an object can have at most one parent.
  10800. *
  10801. * @fires Object3D#added
  10802. * @fires Object3D#childadded
  10803. * @param {Object3D} object - The 3D object to add.
  10804. * @return {Object3D} A reference to this instance.
  10805. */
  10806. add( object ) {
  10807. if ( arguments.length > 1 ) {
  10808. for ( let i = 0; i < arguments.length; i ++ ) {
  10809. this.add( arguments[ i ] );
  10810. }
  10811. return this;
  10812. }
  10813. if ( object === this ) {
  10814. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  10815. return this;
  10816. }
  10817. if ( object && object.isObject3D ) {
  10818. object.removeFromParent();
  10819. object.parent = this;
  10820. this.children.push( object );
  10821. object.dispatchEvent( _addedEvent );
  10822. _childaddedEvent.child = object;
  10823. this.dispatchEvent( _childaddedEvent );
  10824. _childaddedEvent.child = null;
  10825. } else {
  10826. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  10827. }
  10828. return this;
  10829. }
  10830. /**
  10831. * Removes the given 3D object as child from this 3D object.
  10832. * An arbitrary number of objects may be removed.
  10833. *
  10834. * @fires Object3D#removed
  10835. * @fires Object3D#childremoved
  10836. * @param {Object3D} object - The 3D object to remove.
  10837. * @return {Object3D} A reference to this instance.
  10838. */
  10839. remove( object ) {
  10840. if ( arguments.length > 1 ) {
  10841. for ( let i = 0; i < arguments.length; i ++ ) {
  10842. this.remove( arguments[ i ] );
  10843. }
  10844. return this;
  10845. }
  10846. const index = this.children.indexOf( object );
  10847. if ( index !== -1 ) {
  10848. object.parent = null;
  10849. this.children.splice( index, 1 );
  10850. object.dispatchEvent( _removedEvent );
  10851. _childremovedEvent.child = object;
  10852. this.dispatchEvent( _childremovedEvent );
  10853. _childremovedEvent.child = null;
  10854. }
  10855. return this;
  10856. }
  10857. /**
  10858. * Removes this 3D object from its current parent.
  10859. *
  10860. * @fires Object3D#removed
  10861. * @fires Object3D#childremoved
  10862. * @return {Object3D} A reference to this instance.
  10863. */
  10864. removeFromParent() {
  10865. const parent = this.parent;
  10866. if ( parent !== null ) {
  10867. parent.remove( this );
  10868. }
  10869. return this;
  10870. }
  10871. /**
  10872. * Removes all child objects.
  10873. *
  10874. * @fires Object3D#removed
  10875. * @fires Object3D#childremoved
  10876. * @return {Object3D} A reference to this instance.
  10877. */
  10878. clear() {
  10879. return this.remove( ... this.children );
  10880. }
  10881. /**
  10882. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10883. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10884. *
  10885. * @fires Object3D#added
  10886. * @fires Object3D#childadded
  10887. * @param {Object3D} object - The 3D object to attach.
  10888. * @return {Object3D} A reference to this instance.
  10889. */
  10890. attach( object ) {
  10891. // adds object as a child of this, while maintaining the object's world transform
  10892. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10893. this.updateWorldMatrix( true, false );
  10894. _m1$1.copy( this.matrixWorld ).invert();
  10895. if ( object.parent !== null ) {
  10896. object.parent.updateWorldMatrix( true, false );
  10897. _m1$1.multiply( object.parent.matrixWorld );
  10898. }
  10899. object.applyMatrix4( _m1$1 );
  10900. object.removeFromParent();
  10901. object.parent = this;
  10902. this.children.push( object );
  10903. object.updateWorldMatrix( false, true );
  10904. object.dispatchEvent( _addedEvent );
  10905. _childaddedEvent.child = object;
  10906. this.dispatchEvent( _childaddedEvent );
  10907. _childaddedEvent.child = null;
  10908. return this;
  10909. }
  10910. /**
  10911. * Searches through the 3D object and its children, starting with the 3D object
  10912. * itself, and returns the first with a matching ID.
  10913. *
  10914. * @param {number} id - The id.
  10915. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10916. */
  10917. getObjectById( id ) {
  10918. return this.getObjectByProperty( 'id', id );
  10919. }
  10920. /**
  10921. * Searches through the 3D object and its children, starting with the 3D object
  10922. * itself, and returns the first with a matching name.
  10923. *
  10924. * @param {string} name - The name.
  10925. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10926. */
  10927. getObjectByName( name ) {
  10928. return this.getObjectByProperty( 'name', name );
  10929. }
  10930. /**
  10931. * Searches through the 3D object and its children, starting with the 3D object
  10932. * itself, and returns the first with a matching property value.
  10933. *
  10934. * @param {string} name - The name of the property.
  10935. * @param {any} value - The value.
  10936. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10937. */
  10938. getObjectByProperty( name, value ) {
  10939. if ( this[ name ] === value ) return this;
  10940. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10941. const child = this.children[ i ];
  10942. const object = child.getObjectByProperty( name, value );
  10943. if ( object !== undefined ) {
  10944. return object;
  10945. }
  10946. }
  10947. return undefined;
  10948. }
  10949. /**
  10950. * Searches through the 3D object and its children, starting with the 3D object
  10951. * itself, and returns all 3D objects with a matching property value.
  10952. *
  10953. * @param {string} name - The name of the property.
  10954. * @param {any} value - The value.
  10955. * @param {Array<Object3D>} result - The method stores the result in this array.
  10956. * @return {Array<Object3D>} The found 3D objects.
  10957. */
  10958. getObjectsByProperty( name, value, result = [] ) {
  10959. if ( this[ name ] === value ) result.push( this );
  10960. const children = this.children;
  10961. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10962. children[ i ].getObjectsByProperty( name, value, result );
  10963. }
  10964. return result;
  10965. }
  10966. /**
  10967. * Returns a vector representing the position of the 3D object in world space.
  10968. *
  10969. * @param {Vector3} target - The target vector the result is stored to.
  10970. * @return {Vector3} The 3D object's position in world space.
  10971. */
  10972. getWorldPosition( target ) {
  10973. this.updateWorldMatrix( true, false );
  10974. return target.setFromMatrixPosition( this.matrixWorld );
  10975. }
  10976. /**
  10977. * Returns a Quaternion representing the position of the 3D object in world space.
  10978. *
  10979. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10980. * @return {Quaternion} The 3D object's rotation in world space.
  10981. */
  10982. getWorldQuaternion( target ) {
  10983. this.updateWorldMatrix( true, false );
  10984. this.matrixWorld.decompose( _position$4, target, _scale$3 );
  10985. return target;
  10986. }
  10987. /**
  10988. * Returns a vector representing the scale of the 3D object in world space.
  10989. *
  10990. * @param {Vector3} target - The target vector the result is stored to.
  10991. * @return {Vector3} The 3D object's scale in world space.
  10992. */
  10993. getWorldScale( target ) {
  10994. this.updateWorldMatrix( true, false );
  10995. this.matrixWorld.decompose( _position$4, _quaternion$3, target );
  10996. return target;
  10997. }
  10998. /**
  10999. * Returns a vector representing the ("look") direction of the 3D object in world space.
  11000. *
  11001. * @param {Vector3} target - The target vector the result is stored to.
  11002. * @return {Vector3} The 3D object's direction in world space.
  11003. */
  11004. getWorldDirection( target ) {
  11005. this.updateWorldMatrix( true, false );
  11006. const e = this.matrixWorld.elements;
  11007. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  11008. }
  11009. /**
  11010. * Abstract method to get intersections between a casted ray and this
  11011. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  11012. * implement this method in order to use raycasting.
  11013. *
  11014. * @abstract
  11015. * @param {Raycaster} raycaster - The raycaster.
  11016. * @param {Array<Object>} intersects - An array holding the result of the method.
  11017. */
  11018. raycast( /* raycaster, intersects */ ) {}
  11019. /**
  11020. * Executes the callback on this 3D object and all descendants.
  11021. *
  11022. * Note: Modifying the scene graph inside the callback is discouraged.
  11023. *
  11024. * @param {Function} callback - A callback function that allows to process the current 3D object.
  11025. */
  11026. traverse( callback ) {
  11027. callback( this );
  11028. const children = this.children;
  11029. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11030. children[ i ].traverse( callback );
  11031. }
  11032. }
  11033. /**
  11034. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  11035. * Descendants of invisible 3D objects are not traversed.
  11036. *
  11037. * Note: Modifying the scene graph inside the callback is discouraged.
  11038. *
  11039. * @param {Function} callback - A callback function that allows to process the current 3D object.
  11040. */
  11041. traverseVisible( callback ) {
  11042. if ( this.visible === false ) return;
  11043. callback( this );
  11044. const children = this.children;
  11045. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11046. children[ i ].traverseVisible( callback );
  11047. }
  11048. }
  11049. /**
  11050. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  11051. *
  11052. * Note: Modifying the scene graph inside the callback is discouraged.
  11053. *
  11054. * @param {Function} callback - A callback function that allows to process the current 3D object.
  11055. */
  11056. traverseAncestors( callback ) {
  11057. const parent = this.parent;
  11058. if ( parent !== null ) {
  11059. callback( parent );
  11060. parent.traverseAncestors( callback );
  11061. }
  11062. }
  11063. /**
  11064. * Updates the transformation matrix in local space by computing it from the current
  11065. * position, rotation and scale values.
  11066. */
  11067. updateMatrix() {
  11068. this.matrix.compose( this.position, this.quaternion, this.scale );
  11069. const pivot = this.pivot;
  11070. if ( pivot !== null ) {
  11071. const px = pivot.x, py = pivot.y, pz = pivot.z;
  11072. const te = this.matrix.elements;
  11073. te[ 12 ] += px - te[ 0 ] * px - te[ 4 ] * py - te[ 8 ] * pz;
  11074. te[ 13 ] += py - te[ 1 ] * px - te[ 5 ] * py - te[ 9 ] * pz;
  11075. te[ 14 ] += pz - te[ 2 ] * px - te[ 6 ] * py - te[ 10 ] * pz;
  11076. }
  11077. this.matrixWorldNeedsUpdate = true;
  11078. }
  11079. /**
  11080. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  11081. *
  11082. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  11083. * local space. The computation of the local and world matrix can be controlled with the
  11084. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  11085. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  11086. *
  11087. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  11088. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  11089. */
  11090. updateMatrixWorld( force ) {
  11091. if ( this.matrixAutoUpdate ) this.updateMatrix();
  11092. if ( this.matrixWorldNeedsUpdate || force ) {
  11093. if ( this.matrixWorldAutoUpdate === true ) {
  11094. if ( this.parent === null ) {
  11095. this.matrixWorld.copy( this.matrix );
  11096. } else {
  11097. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  11098. }
  11099. }
  11100. this.matrixWorldNeedsUpdate = false;
  11101. force = true;
  11102. }
  11103. // make sure descendants are updated if required
  11104. const children = this.children;
  11105. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11106. const child = children[ i ];
  11107. child.updateMatrixWorld( force );
  11108. }
  11109. }
  11110. /**
  11111. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  11112. * update of ancestor and descendant nodes.
  11113. *
  11114. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  11115. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  11116. */
  11117. updateWorldMatrix( updateParents, updateChildren ) {
  11118. const parent = this.parent;
  11119. if ( updateParents === true && parent !== null ) {
  11120. parent.updateWorldMatrix( true, false );
  11121. }
  11122. if ( this.matrixAutoUpdate ) this.updateMatrix();
  11123. if ( this.matrixWorldAutoUpdate === true ) {
  11124. if ( this.parent === null ) {
  11125. this.matrixWorld.copy( this.matrix );
  11126. } else {
  11127. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  11128. }
  11129. }
  11130. // make sure descendants are updated
  11131. if ( updateChildren === true ) {
  11132. const children = this.children;
  11133. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11134. const child = children[ i ];
  11135. child.updateWorldMatrix( false, true );
  11136. }
  11137. }
  11138. }
  11139. /**
  11140. * Serializes the 3D object into JSON.
  11141. *
  11142. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11143. * @return {Object} A JSON object representing the serialized 3D object.
  11144. * @see {@link ObjectLoader#parse}
  11145. */
  11146. toJSON( meta ) {
  11147. // meta is a string when called from JSON.stringify
  11148. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  11149. const output = {};
  11150. // meta is a hash used to collect geometries, materials.
  11151. // not providing it implies that this is the root object
  11152. // being serialized.
  11153. if ( isRootObject ) {
  11154. // initialize meta obj
  11155. meta = {
  11156. geometries: {},
  11157. materials: {},
  11158. textures: {},
  11159. images: {},
  11160. shapes: {},
  11161. skeletons: {},
  11162. animations: {},
  11163. nodes: {}
  11164. };
  11165. output.metadata = {
  11166. version: 4.7,
  11167. type: 'Object',
  11168. generator: 'Object3D.toJSON'
  11169. };
  11170. }
  11171. // standard Object3D serialization
  11172. const object = {};
  11173. object.uuid = this.uuid;
  11174. object.type = this.type;
  11175. if ( this.name !== '' ) object.name = this.name;
  11176. if ( this.castShadow === true ) object.castShadow = true;
  11177. if ( this.receiveShadow === true ) object.receiveShadow = true;
  11178. if ( this.visible === false ) object.visible = false;
  11179. if ( this.frustumCulled === false ) object.frustumCulled = false;
  11180. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  11181. if ( this.static !== false ) object.static = this.static;
  11182. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  11183. object.layers = this.layers.mask;
  11184. object.matrix = this.matrix.toArray();
  11185. object.up = this.up.toArray();
  11186. if ( this.pivot !== null ) object.pivot = this.pivot.toArray();
  11187. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  11188. // object specific properties
  11189. if ( this.isInstancedMesh ) {
  11190. object.type = 'InstancedMesh';
  11191. object.count = this.count;
  11192. object.instanceMatrix = this.instanceMatrix.toJSON();
  11193. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  11194. }
  11195. if ( this.isBatchedMesh ) {
  11196. object.type = 'BatchedMesh';
  11197. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  11198. object.sortObjects = this.sortObjects;
  11199. object.drawRanges = this._drawRanges;
  11200. object.reservedRanges = this._reservedRanges;
  11201. object.geometryInfo = this._geometryInfo.map( info => ( {
  11202. ...info,
  11203. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  11204. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  11205. } ) );
  11206. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  11207. object.availableInstanceIds = this._availableInstanceIds.slice();
  11208. object.availableGeometryIds = this._availableGeometryIds.slice();
  11209. object.nextIndexStart = this._nextIndexStart;
  11210. object.nextVertexStart = this._nextVertexStart;
  11211. object.geometryCount = this._geometryCount;
  11212. object.maxInstanceCount = this._maxInstanceCount;
  11213. object.maxVertexCount = this._maxVertexCount;
  11214. object.maxIndexCount = this._maxIndexCount;
  11215. object.geometryInitialized = this._geometryInitialized;
  11216. object.matricesTexture = this._matricesTexture.toJSON( meta );
  11217. object.indirectTexture = this._indirectTexture.toJSON( meta );
  11218. if ( this._colorsTexture !== null ) {
  11219. object.colorsTexture = this._colorsTexture.toJSON( meta );
  11220. }
  11221. if ( this.boundingSphere !== null ) {
  11222. object.boundingSphere = this.boundingSphere.toJSON();
  11223. }
  11224. if ( this.boundingBox !== null ) {
  11225. object.boundingBox = this.boundingBox.toJSON();
  11226. }
  11227. }
  11228. //
  11229. function serialize( library, element ) {
  11230. if ( library[ element.uuid ] === undefined ) {
  11231. library[ element.uuid ] = element.toJSON( meta );
  11232. }
  11233. return element.uuid;
  11234. }
  11235. if ( this.isScene ) {
  11236. if ( this.background ) {
  11237. if ( this.background.isColor ) {
  11238. object.background = this.background.toJSON();
  11239. } else if ( this.background.isTexture ) {
  11240. object.background = this.background.toJSON( meta ).uuid;
  11241. }
  11242. }
  11243. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  11244. object.environment = this.environment.toJSON( meta ).uuid;
  11245. }
  11246. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  11247. object.geometry = serialize( meta.geometries, this.geometry );
  11248. const parameters = this.geometry.parameters;
  11249. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  11250. const shapes = parameters.shapes;
  11251. if ( Array.isArray( shapes ) ) {
  11252. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  11253. const shape = shapes[ i ];
  11254. serialize( meta.shapes, shape );
  11255. }
  11256. } else {
  11257. serialize( meta.shapes, shapes );
  11258. }
  11259. }
  11260. }
  11261. if ( this.isSkinnedMesh ) {
  11262. object.bindMode = this.bindMode;
  11263. object.bindMatrix = this.bindMatrix.toArray();
  11264. if ( this.skeleton !== undefined ) {
  11265. serialize( meta.skeletons, this.skeleton );
  11266. object.skeleton = this.skeleton.uuid;
  11267. }
  11268. }
  11269. if ( this.material !== undefined ) {
  11270. if ( Array.isArray( this.material ) ) {
  11271. const uuids = [];
  11272. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11273. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11274. }
  11275. object.material = uuids;
  11276. } else {
  11277. object.material = serialize( meta.materials, this.material );
  11278. }
  11279. }
  11280. //
  11281. if ( this.children.length > 0 ) {
  11282. object.children = [];
  11283. for ( let i = 0; i < this.children.length; i ++ ) {
  11284. object.children.push( this.children[ i ].toJSON( meta ).object );
  11285. }
  11286. }
  11287. //
  11288. if ( this.animations.length > 0 ) {
  11289. object.animations = [];
  11290. for ( let i = 0; i < this.animations.length; i ++ ) {
  11291. const animation = this.animations[ i ];
  11292. object.animations.push( serialize( meta.animations, animation ) );
  11293. }
  11294. }
  11295. if ( isRootObject ) {
  11296. const geometries = extractFromCache( meta.geometries );
  11297. const materials = extractFromCache( meta.materials );
  11298. const textures = extractFromCache( meta.textures );
  11299. const images = extractFromCache( meta.images );
  11300. const shapes = extractFromCache( meta.shapes );
  11301. const skeletons = extractFromCache( meta.skeletons );
  11302. const animations = extractFromCache( meta.animations );
  11303. const nodes = extractFromCache( meta.nodes );
  11304. if ( geometries.length > 0 ) output.geometries = geometries;
  11305. if ( materials.length > 0 ) output.materials = materials;
  11306. if ( textures.length > 0 ) output.textures = textures;
  11307. if ( images.length > 0 ) output.images = images;
  11308. if ( shapes.length > 0 ) output.shapes = shapes;
  11309. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11310. if ( animations.length > 0 ) output.animations = animations;
  11311. if ( nodes.length > 0 ) output.nodes = nodes;
  11312. }
  11313. output.object = object;
  11314. return output;
  11315. // extract data from the cache hash
  11316. // remove metadata on each item
  11317. // and return as array
  11318. function extractFromCache( cache ) {
  11319. const values = [];
  11320. for ( const key in cache ) {
  11321. const data = cache[ key ];
  11322. delete data.metadata;
  11323. values.push( data );
  11324. }
  11325. return values;
  11326. }
  11327. }
  11328. /**
  11329. * Returns a new 3D object with copied values from this instance.
  11330. *
  11331. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11332. * @return {Object3D} A clone of this instance.
  11333. */
  11334. clone( recursive ) {
  11335. return new this.constructor().copy( this, recursive );
  11336. }
  11337. /**
  11338. * Copies the values of the given 3D object to this instance.
  11339. *
  11340. * @param {Object3D} source - The 3D object to copy.
  11341. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11342. * @return {Object3D} A reference to this instance.
  11343. */
  11344. copy( source, recursive = true ) {
  11345. this.name = source.name;
  11346. this.up.copy( source.up );
  11347. this.position.copy( source.position );
  11348. this.rotation.order = source.rotation.order;
  11349. this.quaternion.copy( source.quaternion );
  11350. this.scale.copy( source.scale );
  11351. if ( source.pivot !== null ) {
  11352. this.pivot = source.pivot.clone();
  11353. }
  11354. this.matrix.copy( source.matrix );
  11355. this.matrixWorld.copy( source.matrixWorld );
  11356. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11357. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11358. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11359. this.layers.mask = source.layers.mask;
  11360. this.visible = source.visible;
  11361. this.castShadow = source.castShadow;
  11362. this.receiveShadow = source.receiveShadow;
  11363. this.frustumCulled = source.frustumCulled;
  11364. this.renderOrder = source.renderOrder;
  11365. this.static = source.static;
  11366. this.animations = source.animations.slice();
  11367. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11368. if ( recursive === true ) {
  11369. for ( let i = 0; i < source.children.length; i ++ ) {
  11370. const child = source.children[ i ];
  11371. this.add( child.clone() );
  11372. }
  11373. }
  11374. return this;
  11375. }
  11376. }
  11377. /**
  11378. * The default up direction for objects, also used as the default
  11379. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11380. *
  11381. * @static
  11382. * @type {Vector3}
  11383. * @default (0,1,0)
  11384. */
  11385. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11386. /**
  11387. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11388. * newly created 3D objects.
  11389. *
  11390. * @static
  11391. * @type {boolean}
  11392. * @default true
  11393. */
  11394. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11395. /**
  11396. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11397. * newly created 3D objects.
  11398. *
  11399. * @static
  11400. * @type {boolean}
  11401. * @default true
  11402. */
  11403. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11404. const _v0$1 = /*@__PURE__*/ new Vector3();
  11405. const _v1$3 = /*@__PURE__*/ new Vector3();
  11406. const _v2$2 = /*@__PURE__*/ new Vector3();
  11407. const _v3$2 = /*@__PURE__*/ new Vector3();
  11408. const _vab = /*@__PURE__*/ new Vector3();
  11409. const _vac = /*@__PURE__*/ new Vector3();
  11410. const _vbc = /*@__PURE__*/ new Vector3();
  11411. const _vap = /*@__PURE__*/ new Vector3();
  11412. const _vbp = /*@__PURE__*/ new Vector3();
  11413. const _vcp = /*@__PURE__*/ new Vector3();
  11414. const _v40 = /*@__PURE__*/ new Vector4();
  11415. const _v41 = /*@__PURE__*/ new Vector4();
  11416. const _v42 = /*@__PURE__*/ new Vector4();
  11417. /**
  11418. * A geometric triangle as defined by three vectors representing its three corners.
  11419. */
  11420. class Triangle {
  11421. /**
  11422. * Constructs a new triangle.
  11423. *
  11424. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11425. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11426. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11427. */
  11428. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11429. /**
  11430. * The first corner of the triangle.
  11431. *
  11432. * @type {Vector3}
  11433. */
  11434. this.a = a;
  11435. /**
  11436. * The second corner of the triangle.
  11437. *
  11438. * @type {Vector3}
  11439. */
  11440. this.b = b;
  11441. /**
  11442. * The third corner of the triangle.
  11443. *
  11444. * @type {Vector3}
  11445. */
  11446. this.c = c;
  11447. }
  11448. /**
  11449. * Computes the normal vector of a triangle.
  11450. *
  11451. * @param {Vector3} a - The first corner of the triangle.
  11452. * @param {Vector3} b - The second corner of the triangle.
  11453. * @param {Vector3} c - The third corner of the triangle.
  11454. * @param {Vector3} target - The target vector that is used to store the method's result.
  11455. * @return {Vector3} The triangle's normal.
  11456. */
  11457. static getNormal( a, b, c, target ) {
  11458. target.subVectors( c, b );
  11459. _v0$1.subVectors( a, b );
  11460. target.cross( _v0$1 );
  11461. const targetLengthSq = target.lengthSq();
  11462. if ( targetLengthSq > 0 ) {
  11463. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11464. }
  11465. return target.set( 0, 0, 0 );
  11466. }
  11467. /**
  11468. * Computes a barycentric coordinates from the given vector.
  11469. * Returns `null` if the triangle is degenerate.
  11470. *
  11471. * @param {Vector3} point - A point in 3D space.
  11472. * @param {Vector3} a - The first corner of the triangle.
  11473. * @param {Vector3} b - The second corner of the triangle.
  11474. * @param {Vector3} c - The third corner of the triangle.
  11475. * @param {Vector3} target - The target vector that is used to store the method's result.
  11476. * @return {?Vector3} The barycentric coordinates for the given point
  11477. */
  11478. static getBarycoord( point, a, b, c, target ) {
  11479. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11480. _v0$1.subVectors( c, a );
  11481. _v1$3.subVectors( b, a );
  11482. _v2$2.subVectors( point, a );
  11483. const dot00 = _v0$1.dot( _v0$1 );
  11484. const dot01 = _v0$1.dot( _v1$3 );
  11485. const dot02 = _v0$1.dot( _v2$2 );
  11486. const dot11 = _v1$3.dot( _v1$3 );
  11487. const dot12 = _v1$3.dot( _v2$2 );
  11488. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11489. // collinear or singular triangle
  11490. if ( denom === 0 ) {
  11491. target.set( 0, 0, 0 );
  11492. return null;
  11493. }
  11494. const invDenom = 1 / denom;
  11495. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11496. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11497. // barycentric coordinates must always sum to 1
  11498. return target.set( 1 - u - v, v, u );
  11499. }
  11500. /**
  11501. * Returns `true` if the given point, when projected onto the plane of the
  11502. * triangle, lies within the triangle.
  11503. *
  11504. * @param {Vector3} point - The point in 3D space to test.
  11505. * @param {Vector3} a - The first corner of the triangle.
  11506. * @param {Vector3} b - The second corner of the triangle.
  11507. * @param {Vector3} c - The third corner of the triangle.
  11508. * @return {boolean} Whether the given point, when projected onto the plane of the
  11509. * triangle, lies within the triangle or not.
  11510. */
  11511. static containsPoint( point, a, b, c ) {
  11512. // if the triangle is degenerate then we can't contain a point
  11513. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11514. return false;
  11515. }
  11516. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11517. }
  11518. /**
  11519. * Computes the value barycentrically interpolated for the given point on the
  11520. * triangle. Returns `null` if the triangle is degenerate.
  11521. *
  11522. * @param {Vector3} point - Position of interpolated point.
  11523. * @param {Vector3} p1 - The first corner of the triangle.
  11524. * @param {Vector3} p2 - The second corner of the triangle.
  11525. * @param {Vector3} p3 - The third corner of the triangle.
  11526. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11527. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11528. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11529. * @param {Vector3} target - The target vector that is used to store the method's result.
  11530. * @return {?Vector3} The interpolated value.
  11531. */
  11532. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11533. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11534. target.x = 0;
  11535. target.y = 0;
  11536. if ( 'z' in target ) target.z = 0;
  11537. if ( 'w' in target ) target.w = 0;
  11538. return null;
  11539. }
  11540. target.setScalar( 0 );
  11541. target.addScaledVector( v1, _v3$2.x );
  11542. target.addScaledVector( v2, _v3$2.y );
  11543. target.addScaledVector( v3, _v3$2.z );
  11544. return target;
  11545. }
  11546. /**
  11547. * Computes the value barycentrically interpolated for the given attribute and indices.
  11548. *
  11549. * @param {BufferAttribute} attr - The attribute to interpolate.
  11550. * @param {number} i1 - Index of first vertex.
  11551. * @param {number} i2 - Index of second vertex.
  11552. * @param {number} i3 - Index of third vertex.
  11553. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11554. * @param {Vector3} target - The target vector that is used to store the method's result.
  11555. * @return {Vector3} The interpolated attribute value.
  11556. */
  11557. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11558. _v40.setScalar( 0 );
  11559. _v41.setScalar( 0 );
  11560. _v42.setScalar( 0 );
  11561. _v40.fromBufferAttribute( attr, i1 );
  11562. _v41.fromBufferAttribute( attr, i2 );
  11563. _v42.fromBufferAttribute( attr, i3 );
  11564. target.setScalar( 0 );
  11565. target.addScaledVector( _v40, barycoord.x );
  11566. target.addScaledVector( _v41, barycoord.y );
  11567. target.addScaledVector( _v42, barycoord.z );
  11568. return target;
  11569. }
  11570. /**
  11571. * Returns `true` if the triangle is oriented towards the given direction.
  11572. *
  11573. * @param {Vector3} a - The first corner of the triangle.
  11574. * @param {Vector3} b - The second corner of the triangle.
  11575. * @param {Vector3} c - The third corner of the triangle.
  11576. * @param {Vector3} direction - The (normalized) direction vector.
  11577. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11578. */
  11579. static isFrontFacing( a, b, c, direction ) {
  11580. _v0$1.subVectors( c, b );
  11581. _v1$3.subVectors( a, b );
  11582. // strictly front facing
  11583. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11584. }
  11585. /**
  11586. * Sets the triangle's vertices by copying the given values.
  11587. *
  11588. * @param {Vector3} a - The first corner of the triangle.
  11589. * @param {Vector3} b - The second corner of the triangle.
  11590. * @param {Vector3} c - The third corner of the triangle.
  11591. * @return {Triangle} A reference to this triangle.
  11592. */
  11593. set( a, b, c ) {
  11594. this.a.copy( a );
  11595. this.b.copy( b );
  11596. this.c.copy( c );
  11597. return this;
  11598. }
  11599. /**
  11600. * Sets the triangle's vertices by copying the given array values.
  11601. *
  11602. * @param {Array<Vector3>} points - An array with 3D points.
  11603. * @param {number} i0 - The array index representing the first corner of the triangle.
  11604. * @param {number} i1 - The array index representing the second corner of the triangle.
  11605. * @param {number} i2 - The array index representing the third corner of the triangle.
  11606. * @return {Triangle} A reference to this triangle.
  11607. */
  11608. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11609. this.a.copy( points[ i0 ] );
  11610. this.b.copy( points[ i1 ] );
  11611. this.c.copy( points[ i2 ] );
  11612. return this;
  11613. }
  11614. /**
  11615. * Sets the triangle's vertices by copying the given attribute values.
  11616. *
  11617. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11618. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11619. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11620. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11621. * @return {Triangle} A reference to this triangle.
  11622. */
  11623. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11624. this.a.fromBufferAttribute( attribute, i0 );
  11625. this.b.fromBufferAttribute( attribute, i1 );
  11626. this.c.fromBufferAttribute( attribute, i2 );
  11627. return this;
  11628. }
  11629. /**
  11630. * Returns a new triangle with copied values from this instance.
  11631. *
  11632. * @return {Triangle} A clone of this instance.
  11633. */
  11634. clone() {
  11635. return new this.constructor().copy( this );
  11636. }
  11637. /**
  11638. * Copies the values of the given triangle to this instance.
  11639. *
  11640. * @param {Triangle} triangle - The triangle to copy.
  11641. * @return {Triangle} A reference to this triangle.
  11642. */
  11643. copy( triangle ) {
  11644. this.a.copy( triangle.a );
  11645. this.b.copy( triangle.b );
  11646. this.c.copy( triangle.c );
  11647. return this;
  11648. }
  11649. /**
  11650. * Computes the area of the triangle.
  11651. *
  11652. * @return {number} The triangle's area.
  11653. */
  11654. getArea() {
  11655. _v0$1.subVectors( this.c, this.b );
  11656. _v1$3.subVectors( this.a, this.b );
  11657. return _v0$1.cross( _v1$3 ).length() * 0.5;
  11658. }
  11659. /**
  11660. * Computes the midpoint of the triangle.
  11661. *
  11662. * @param {Vector3} target - The target vector that is used to store the method's result.
  11663. * @return {Vector3} The triangle's midpoint.
  11664. */
  11665. getMidpoint( target ) {
  11666. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11667. }
  11668. /**
  11669. * Computes the normal of the triangle.
  11670. *
  11671. * @param {Vector3} target - The target vector that is used to store the method's result.
  11672. * @return {Vector3} The triangle's normal.
  11673. */
  11674. getNormal( target ) {
  11675. return Triangle.getNormal( this.a, this.b, this.c, target );
  11676. }
  11677. /**
  11678. * Computes a plane the triangle lies within.
  11679. *
  11680. * @param {Plane} target - The target vector that is used to store the method's result.
  11681. * @return {Plane} The plane the triangle lies within.
  11682. */
  11683. getPlane( target ) {
  11684. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11685. }
  11686. /**
  11687. * Computes a barycentric coordinates from the given vector.
  11688. * Returns `null` if the triangle is degenerate.
  11689. *
  11690. * @param {Vector3} point - A point in 3D space.
  11691. * @param {Vector3} target - The target vector that is used to store the method's result.
  11692. * @return {?Vector3} The barycentric coordinates for the given point
  11693. */
  11694. getBarycoord( point, target ) {
  11695. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11696. }
  11697. /**
  11698. * Computes the value barycentrically interpolated for the given point on the
  11699. * triangle. Returns `null` if the triangle is degenerate.
  11700. *
  11701. * @param {Vector3} point - Position of interpolated point.
  11702. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11703. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11704. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11705. * @param {Vector3} target - The target vector that is used to store the method's result.
  11706. * @return {?Vector3} The interpolated value.
  11707. */
  11708. getInterpolation( point, v1, v2, v3, target ) {
  11709. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11710. }
  11711. /**
  11712. * Returns `true` if the given point, when projected onto the plane of the
  11713. * triangle, lies within the triangle.
  11714. *
  11715. * @param {Vector3} point - The point in 3D space to test.
  11716. * @return {boolean} Whether the given point, when projected onto the plane of the
  11717. * triangle, lies within the triangle or not.
  11718. */
  11719. containsPoint( point ) {
  11720. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11721. }
  11722. /**
  11723. * Returns `true` if the triangle is oriented towards the given direction.
  11724. *
  11725. * @param {Vector3} direction - The (normalized) direction vector.
  11726. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11727. */
  11728. isFrontFacing( direction ) {
  11729. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11730. }
  11731. /**
  11732. * Returns `true` if this triangle intersects with the given box.
  11733. *
  11734. * @param {Box3} box - The box to intersect.
  11735. * @return {boolean} Whether this triangle intersects with the given box or not.
  11736. */
  11737. intersectsBox( box ) {
  11738. return box.intersectsTriangle( this );
  11739. }
  11740. /**
  11741. * Returns the closest point on the triangle to the given point.
  11742. *
  11743. * @param {Vector3} p - The point to compute the closest point for.
  11744. * @param {Vector3} target - The target vector that is used to store the method's result.
  11745. * @return {Vector3} The closest point on the triangle.
  11746. */
  11747. closestPointToPoint( p, target ) {
  11748. const a = this.a, b = this.b, c = this.c;
  11749. let v, w;
  11750. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11751. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11752. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11753. // basically, we're distinguishing which of the voronoi regions of the triangle
  11754. // the point lies in with the minimum amount of redundant computation.
  11755. _vab.subVectors( b, a );
  11756. _vac.subVectors( c, a );
  11757. _vap.subVectors( p, a );
  11758. const d1 = _vab.dot( _vap );
  11759. const d2 = _vac.dot( _vap );
  11760. if ( d1 <= 0 && d2 <= 0 ) {
  11761. // vertex region of A; barycentric coords (1, 0, 0)
  11762. return target.copy( a );
  11763. }
  11764. _vbp.subVectors( p, b );
  11765. const d3 = _vab.dot( _vbp );
  11766. const d4 = _vac.dot( _vbp );
  11767. if ( d3 >= 0 && d4 <= d3 ) {
  11768. // vertex region of B; barycentric coords (0, 1, 0)
  11769. return target.copy( b );
  11770. }
  11771. const vc = d1 * d4 - d3 * d2;
  11772. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11773. v = d1 / ( d1 - d3 );
  11774. // edge region of AB; barycentric coords (1-v, v, 0)
  11775. return target.copy( a ).addScaledVector( _vab, v );
  11776. }
  11777. _vcp.subVectors( p, c );
  11778. const d5 = _vab.dot( _vcp );
  11779. const d6 = _vac.dot( _vcp );
  11780. if ( d6 >= 0 && d5 <= d6 ) {
  11781. // vertex region of C; barycentric coords (0, 0, 1)
  11782. return target.copy( c );
  11783. }
  11784. const vb = d5 * d2 - d1 * d6;
  11785. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11786. w = d2 / ( d2 - d6 );
  11787. // edge region of AC; barycentric coords (1-w, 0, w)
  11788. return target.copy( a ).addScaledVector( _vac, w );
  11789. }
  11790. const va = d3 * d6 - d5 * d4;
  11791. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11792. _vbc.subVectors( c, b );
  11793. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11794. // edge region of BC; barycentric coords (0, 1-w, w)
  11795. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11796. }
  11797. // face region
  11798. const denom = 1 / ( va + vb + vc );
  11799. // u = va * denom
  11800. v = vb * denom;
  11801. w = vc * denom;
  11802. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11803. }
  11804. /**
  11805. * Returns `true` if this triangle is equal with the given one.
  11806. *
  11807. * @param {Triangle} triangle - The triangle to test for equality.
  11808. * @return {boolean} Whether this triangle is equal with the given one.
  11809. */
  11810. equals( triangle ) {
  11811. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11812. }
  11813. }
  11814. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11815. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11816. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11817. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11818. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11819. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11820. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11821. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11822. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11823. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11824. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11825. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11826. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11827. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11828. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11829. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11830. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11831. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11832. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11833. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11834. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11835. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11836. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11837. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11838. const _hslA = { h: 0, s: 0, l: 0 };
  11839. const _hslB = { h: 0, s: 0, l: 0 };
  11840. function hue2rgb( p, q, t ) {
  11841. if ( t < 0 ) t += 1;
  11842. if ( t > 1 ) t -= 1;
  11843. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11844. if ( t < 1 / 2 ) return q;
  11845. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11846. return p;
  11847. }
  11848. /**
  11849. * A Color instance is represented by RGB components in the linear <i>working
  11850. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11851. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11852. * strings) are converted to the working color space automatically.
  11853. *
  11854. * ```js
  11855. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11856. * const color = new THREE.Color().setHex( 0x112233 );
  11857. * ```
  11858. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11859. * ```js
  11860. * // assumed already LinearSRGBColorSpace; no conversion
  11861. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11862. *
  11863. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11864. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11865. * ```
  11866. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11867. * see <i>Color management</i>. Iterating through a Color instance will yield
  11868. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11869. * in any of the following ways:
  11870. * ```js
  11871. * //empty constructor - will default white
  11872. * const color1 = new THREE.Color();
  11873. *
  11874. * //Hexadecimal color (recommended)
  11875. * const color2 = new THREE.Color( 0xff0000 );
  11876. *
  11877. * //RGB string
  11878. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11879. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11880. *
  11881. * //X11 color name - all 140 color names are supported.
  11882. * //Note the lack of CamelCase in the name
  11883. * const color5 = new THREE.Color( 'skyblue' );
  11884. * //HSL string
  11885. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11886. *
  11887. * //Separate RGB values between 0 and 1
  11888. * const color7 = new THREE.Color( 1, 0, 0 );
  11889. * ```
  11890. */
  11891. class Color {
  11892. /**
  11893. * Constructs a new color.
  11894. *
  11895. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11896. * and that method is used throughout the rest of the documentation.
  11897. *
  11898. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11899. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11900. * @param {number} [g] - The green component.
  11901. * @param {number} [b] - The blue component.
  11902. */
  11903. constructor( r, g, b ) {
  11904. /**
  11905. * This flag can be used for type testing.
  11906. *
  11907. * @type {boolean}
  11908. * @readonly
  11909. * @default true
  11910. */
  11911. this.isColor = true;
  11912. /**
  11913. * The red component.
  11914. *
  11915. * @type {number}
  11916. * @default 1
  11917. */
  11918. this.r = 1;
  11919. /**
  11920. * The green component.
  11921. *
  11922. * @type {number}
  11923. * @default 1
  11924. */
  11925. this.g = 1;
  11926. /**
  11927. * The blue component.
  11928. *
  11929. * @type {number}
  11930. * @default 1
  11931. */
  11932. this.b = 1;
  11933. return this.set( r, g, b );
  11934. }
  11935. /**
  11936. * Sets the colors's components from the given values.
  11937. *
  11938. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11939. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11940. * @param {number} [g] - The green component.
  11941. * @param {number} [b] - The blue component.
  11942. * @return {Color} A reference to this color.
  11943. */
  11944. set( r, g, b ) {
  11945. if ( g === undefined && b === undefined ) {
  11946. // r is THREE.Color, hex or string
  11947. const value = r;
  11948. if ( value && value.isColor ) {
  11949. this.copy( value );
  11950. } else if ( typeof value === 'number' ) {
  11951. this.setHex( value );
  11952. } else if ( typeof value === 'string' ) {
  11953. this.setStyle( value );
  11954. }
  11955. } else {
  11956. this.setRGB( r, g, b );
  11957. }
  11958. return this;
  11959. }
  11960. /**
  11961. * Sets the colors's components to the given scalar value.
  11962. *
  11963. * @param {number} scalar - The scalar value.
  11964. * @return {Color} A reference to this color.
  11965. */
  11966. setScalar( scalar ) {
  11967. this.r = scalar;
  11968. this.g = scalar;
  11969. this.b = scalar;
  11970. return this;
  11971. }
  11972. /**
  11973. * Sets this color from a hexadecimal value.
  11974. *
  11975. * @param {number} hex - The hexadecimal value.
  11976. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11977. * @return {Color} A reference to this color.
  11978. */
  11979. setHex( hex, colorSpace = SRGBColorSpace ) {
  11980. hex = Math.floor( hex );
  11981. this.r = ( hex >> 16 & 255 ) / 255;
  11982. this.g = ( hex >> 8 & 255 ) / 255;
  11983. this.b = ( hex & 255 ) / 255;
  11984. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11985. return this;
  11986. }
  11987. /**
  11988. * Sets this color from RGB values.
  11989. *
  11990. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11991. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11992. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11993. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11994. * @return {Color} A reference to this color.
  11995. */
  11996. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11997. this.r = r;
  11998. this.g = g;
  11999. this.b = b;
  12000. ColorManagement.colorSpaceToWorking( this, colorSpace );
  12001. return this;
  12002. }
  12003. /**
  12004. * Sets this color from RGB values.
  12005. *
  12006. * @param {number} h - Hue value between `0.0` and `1.0`.
  12007. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12008. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12009. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12010. * @return {Color} A reference to this color.
  12011. */
  12012. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  12013. // h,s,l ranges are in 0.0 - 1.0
  12014. h = euclideanModulo( h, 1 );
  12015. s = clamp( s, 0, 1 );
  12016. l = clamp( l, 0, 1 );
  12017. if ( s === 0 ) {
  12018. this.r = this.g = this.b = l;
  12019. } else {
  12020. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  12021. const q = ( 2 * l ) - p;
  12022. this.r = hue2rgb( q, p, h + 1 / 3 );
  12023. this.g = hue2rgb( q, p, h );
  12024. this.b = hue2rgb( q, p, h - 1 / 3 );
  12025. }
  12026. ColorManagement.colorSpaceToWorking( this, colorSpace );
  12027. return this;
  12028. }
  12029. /**
  12030. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  12031. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  12032. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  12033. * all 140 color names are supported).
  12034. *
  12035. * @param {string} style - Color as a CSS-style string.
  12036. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12037. * @return {Color} A reference to this color.
  12038. */
  12039. setStyle( style, colorSpace = SRGBColorSpace ) {
  12040. function handleAlpha( string ) {
  12041. if ( string === undefined ) return;
  12042. if ( parseFloat( string ) < 1 ) {
  12043. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  12044. }
  12045. }
  12046. let m;
  12047. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  12048. // rgb / hsl
  12049. let color;
  12050. const name = m[ 1 ];
  12051. const components = m[ 2 ];
  12052. switch ( name ) {
  12053. case 'rgb':
  12054. case 'rgba':
  12055. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  12056. // rgb(255,0,0) rgba(255,0,0,0.5)
  12057. handleAlpha( color[ 4 ] );
  12058. return this.setRGB(
  12059. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  12060. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  12061. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  12062. colorSpace
  12063. );
  12064. }
  12065. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  12066. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  12067. handleAlpha( color[ 4 ] );
  12068. return this.setRGB(
  12069. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  12070. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  12071. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  12072. colorSpace
  12073. );
  12074. }
  12075. break;
  12076. case 'hsl':
  12077. case 'hsla':
  12078. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  12079. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  12080. handleAlpha( color[ 4 ] );
  12081. return this.setHSL(
  12082. parseFloat( color[ 1 ] ) / 360,
  12083. parseFloat( color[ 2 ] ) / 100,
  12084. parseFloat( color[ 3 ] ) / 100,
  12085. colorSpace
  12086. );
  12087. }
  12088. break;
  12089. default:
  12090. warn( 'Color: Unknown color model ' + style );
  12091. }
  12092. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  12093. // hex color
  12094. const hex = m[ 1 ];
  12095. const size = hex.length;
  12096. if ( size === 3 ) {
  12097. // #ff0
  12098. return this.setRGB(
  12099. parseInt( hex.charAt( 0 ), 16 ) / 15,
  12100. parseInt( hex.charAt( 1 ), 16 ) / 15,
  12101. parseInt( hex.charAt( 2 ), 16 ) / 15,
  12102. colorSpace
  12103. );
  12104. } else if ( size === 6 ) {
  12105. // #ff0000
  12106. return this.setHex( parseInt( hex, 16 ), colorSpace );
  12107. } else {
  12108. warn( 'Color: Invalid hex color ' + style );
  12109. }
  12110. } else if ( style && style.length > 0 ) {
  12111. return this.setColorName( style, colorSpace );
  12112. }
  12113. return this;
  12114. }
  12115. /**
  12116. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  12117. * you don't need the other CSS-style formats.
  12118. *
  12119. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  12120. * ```js
  12121. * Color.NAMES.aliceblue // returns 0xF0F8FF
  12122. * ```
  12123. *
  12124. * @param {string} style - The color name.
  12125. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12126. * @return {Color} A reference to this color.
  12127. */
  12128. setColorName( style, colorSpace = SRGBColorSpace ) {
  12129. // color keywords
  12130. const hex = _colorKeywords[ style.toLowerCase() ];
  12131. if ( hex !== undefined ) {
  12132. // red
  12133. this.setHex( hex, colorSpace );
  12134. } else {
  12135. // unknown color
  12136. warn( 'Color: Unknown color ' + style );
  12137. }
  12138. return this;
  12139. }
  12140. /**
  12141. * Returns a new color with copied values from this instance.
  12142. *
  12143. * @return {Color} A clone of this instance.
  12144. */
  12145. clone() {
  12146. return new this.constructor( this.r, this.g, this.b );
  12147. }
  12148. /**
  12149. * Copies the values of the given color to this instance.
  12150. *
  12151. * @param {Color} color - The color to copy.
  12152. * @return {Color} A reference to this color.
  12153. */
  12154. copy( color ) {
  12155. this.r = color.r;
  12156. this.g = color.g;
  12157. this.b = color.b;
  12158. return this;
  12159. }
  12160. /**
  12161. * Copies the given color into this color, and then converts this color from
  12162. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  12163. *
  12164. * @param {Color} color - The color to copy/convert.
  12165. * @return {Color} A reference to this color.
  12166. */
  12167. copySRGBToLinear( color ) {
  12168. this.r = SRGBToLinear( color.r );
  12169. this.g = SRGBToLinear( color.g );
  12170. this.b = SRGBToLinear( color.b );
  12171. return this;
  12172. }
  12173. /**
  12174. * Copies the given color into this color, and then converts this color from
  12175. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12176. *
  12177. * @param {Color} color - The color to copy/convert.
  12178. * @return {Color} A reference to this color.
  12179. */
  12180. copyLinearToSRGB( color ) {
  12181. this.r = LinearToSRGB( color.r );
  12182. this.g = LinearToSRGB( color.g );
  12183. this.b = LinearToSRGB( color.b );
  12184. return this;
  12185. }
  12186. /**
  12187. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  12188. *
  12189. * @return {Color} A reference to this color.
  12190. */
  12191. convertSRGBToLinear() {
  12192. this.copySRGBToLinear( this );
  12193. return this;
  12194. }
  12195. /**
  12196. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12197. *
  12198. * @return {Color} A reference to this color.
  12199. */
  12200. convertLinearToSRGB() {
  12201. this.copyLinearToSRGB( this );
  12202. return this;
  12203. }
  12204. /**
  12205. * Returns the hexadecimal value of this color.
  12206. *
  12207. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12208. * @return {number} The hexadecimal value.
  12209. */
  12210. getHex( colorSpace = SRGBColorSpace ) {
  12211. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12212. 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 ) );
  12213. }
  12214. /**
  12215. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  12216. *
  12217. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12218. * @return {string} The hexadecimal value as a string.
  12219. */
  12220. getHexString( colorSpace = SRGBColorSpace ) {
  12221. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  12222. }
  12223. /**
  12224. * Converts the colors RGB values into the HSL format and stores them into the
  12225. * given target object.
  12226. *
  12227. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  12228. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12229. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  12230. */
  12231. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  12232. // h,s,l ranges are in 0.0 - 1.0
  12233. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12234. const r = _color.r, g = _color.g, b = _color.b;
  12235. const max = Math.max( r, g, b );
  12236. const min = Math.min( r, g, b );
  12237. let hue, saturation;
  12238. const lightness = ( min + max ) / 2.0;
  12239. if ( min === max ) {
  12240. hue = 0;
  12241. saturation = 0;
  12242. } else {
  12243. const delta = max - min;
  12244. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  12245. switch ( max ) {
  12246. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  12247. case g: hue = ( b - r ) / delta + 2; break;
  12248. case b: hue = ( r - g ) / delta + 4; break;
  12249. }
  12250. hue /= 6;
  12251. }
  12252. target.h = hue;
  12253. target.s = saturation;
  12254. target.l = lightness;
  12255. return target;
  12256. }
  12257. /**
  12258. * Returns the RGB values of this color and stores them into the given target object.
  12259. *
  12260. * @param {Color} target - The target color that is used to store the method's result.
  12261. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12262. * @return {Color} The RGB representation of this color.
  12263. */
  12264. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  12265. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12266. target.r = _color.r;
  12267. target.g = _color.g;
  12268. target.b = _color.b;
  12269. return target;
  12270. }
  12271. /**
  12272. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12273. *
  12274. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12275. * @return {string} The CSS representation of this color.
  12276. */
  12277. getStyle( colorSpace = SRGBColorSpace ) {
  12278. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12279. const r = _color.r, g = _color.g, b = _color.b;
  12280. if ( colorSpace !== SRGBColorSpace ) {
  12281. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12282. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12283. }
  12284. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12285. }
  12286. /**
  12287. * Adds the given HSL values to this color's values.
  12288. * Internally, this converts the color's RGB values to HSL, adds HSL
  12289. * and then converts the color back to RGB.
  12290. *
  12291. * @param {number} h - Hue value between `0.0` and `1.0`.
  12292. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12293. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12294. * @return {Color} A reference to this color.
  12295. */
  12296. offsetHSL( h, s, l ) {
  12297. this.getHSL( _hslA );
  12298. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12299. }
  12300. /**
  12301. * Adds the RGB values of the given color to the RGB values of this color.
  12302. *
  12303. * @param {Color} color - The color to add.
  12304. * @return {Color} A reference to this color.
  12305. */
  12306. add( color ) {
  12307. this.r += color.r;
  12308. this.g += color.g;
  12309. this.b += color.b;
  12310. return this;
  12311. }
  12312. /**
  12313. * Adds the RGB values of the given colors and stores the result in this instance.
  12314. *
  12315. * @param {Color} color1 - The first color.
  12316. * @param {Color} color2 - The second color.
  12317. * @return {Color} A reference to this color.
  12318. */
  12319. addColors( color1, color2 ) {
  12320. this.r = color1.r + color2.r;
  12321. this.g = color1.g + color2.g;
  12322. this.b = color1.b + color2.b;
  12323. return this;
  12324. }
  12325. /**
  12326. * Adds the given scalar value to the RGB values of this color.
  12327. *
  12328. * @param {number} s - The scalar to add.
  12329. * @return {Color} A reference to this color.
  12330. */
  12331. addScalar( s ) {
  12332. this.r += s;
  12333. this.g += s;
  12334. this.b += s;
  12335. return this;
  12336. }
  12337. /**
  12338. * Subtracts the RGB values of the given color from the RGB values of this color.
  12339. *
  12340. * @param {Color} color - The color to subtract.
  12341. * @return {Color} A reference to this color.
  12342. */
  12343. sub( color ) {
  12344. this.r = Math.max( 0, this.r - color.r );
  12345. this.g = Math.max( 0, this.g - color.g );
  12346. this.b = Math.max( 0, this.b - color.b );
  12347. return this;
  12348. }
  12349. /**
  12350. * Multiplies the RGB values of the given color with the RGB values of this color.
  12351. *
  12352. * @param {Color} color - The color to multiply.
  12353. * @return {Color} A reference to this color.
  12354. */
  12355. multiply( color ) {
  12356. this.r *= color.r;
  12357. this.g *= color.g;
  12358. this.b *= color.b;
  12359. return this;
  12360. }
  12361. /**
  12362. * Multiplies the given scalar value with the RGB values of this color.
  12363. *
  12364. * @param {number} s - The scalar to multiply.
  12365. * @return {Color} A reference to this color.
  12366. */
  12367. multiplyScalar( s ) {
  12368. this.r *= s;
  12369. this.g *= s;
  12370. this.b *= s;
  12371. return this;
  12372. }
  12373. /**
  12374. * Linearly interpolates this color's RGB values toward the RGB values of the
  12375. * given color. The alpha argument can be thought of as the ratio between
  12376. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12377. *
  12378. * @param {Color} color - The color to converge on.
  12379. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12380. * @return {Color} A reference to this color.
  12381. */
  12382. lerp( color, alpha ) {
  12383. this.r += ( color.r - this.r ) * alpha;
  12384. this.g += ( color.g - this.g ) * alpha;
  12385. this.b += ( color.b - this.b ) * alpha;
  12386. return this;
  12387. }
  12388. /**
  12389. * Linearly interpolates between the given colors and stores the result in this instance.
  12390. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12391. * is the first and `1.0` is the second color.
  12392. *
  12393. * @param {Color} color1 - The first color.
  12394. * @param {Color} color2 - The second color.
  12395. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12396. * @return {Color} A reference to this color.
  12397. */
  12398. lerpColors( color1, color2, alpha ) {
  12399. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12400. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12401. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12402. return this;
  12403. }
  12404. /**
  12405. * Linearly interpolates this color's HSL values toward the HSL values of the
  12406. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12407. * from one color to the other, but instead going through all the hues in between
  12408. * those two colors. The alpha argument can be thought of as the ratio between
  12409. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12410. *
  12411. * @param {Color} color - The color to converge on.
  12412. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12413. * @return {Color} A reference to this color.
  12414. */
  12415. lerpHSL( color, alpha ) {
  12416. this.getHSL( _hslA );
  12417. color.getHSL( _hslB );
  12418. const h = lerp( _hslA.h, _hslB.h, alpha );
  12419. const s = lerp( _hslA.s, _hslB.s, alpha );
  12420. const l = lerp( _hslA.l, _hslB.l, alpha );
  12421. this.setHSL( h, s, l );
  12422. return this;
  12423. }
  12424. /**
  12425. * Sets the color's RGB components from the given 3D vector.
  12426. *
  12427. * @param {Vector3} v - The vector to set.
  12428. * @return {Color} A reference to this color.
  12429. */
  12430. setFromVector3( v ) {
  12431. this.r = v.x;
  12432. this.g = v.y;
  12433. this.b = v.z;
  12434. return this;
  12435. }
  12436. /**
  12437. * Transforms this color with the given 3x3 matrix.
  12438. *
  12439. * @param {Matrix3} m - The matrix.
  12440. * @return {Color} A reference to this color.
  12441. */
  12442. applyMatrix3( m ) {
  12443. const r = this.r, g = this.g, b = this.b;
  12444. const e = m.elements;
  12445. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12446. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12447. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12448. return this;
  12449. }
  12450. /**
  12451. * Returns `true` if this color is equal with the given one.
  12452. *
  12453. * @param {Color} c - The color to test for equality.
  12454. * @return {boolean} Whether this bounding color is equal with the given one.
  12455. */
  12456. equals( c ) {
  12457. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12458. }
  12459. /**
  12460. * Sets this color's RGB components from the given array.
  12461. *
  12462. * @param {Array<number>} array - An array holding the RGB values.
  12463. * @param {number} [offset=0] - The offset into the array.
  12464. * @return {Color} A reference to this color.
  12465. */
  12466. fromArray( array, offset = 0 ) {
  12467. this.r = array[ offset ];
  12468. this.g = array[ offset + 1 ];
  12469. this.b = array[ offset + 2 ];
  12470. return this;
  12471. }
  12472. /**
  12473. * Writes the RGB components of this color to the given array. If no array is provided,
  12474. * the method returns a new instance.
  12475. *
  12476. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12477. * @param {number} [offset=0] - Index of the first element in the array.
  12478. * @return {Array<number>} The color components.
  12479. */
  12480. toArray( array = [], offset = 0 ) {
  12481. array[ offset ] = this.r;
  12482. array[ offset + 1 ] = this.g;
  12483. array[ offset + 2 ] = this.b;
  12484. return array;
  12485. }
  12486. /**
  12487. * Sets the components of this color from the given buffer attribute.
  12488. *
  12489. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12490. * @param {number} index - The index into the attribute.
  12491. * @return {Color} A reference to this color.
  12492. */
  12493. fromBufferAttribute( attribute, index ) {
  12494. this.r = attribute.getX( index );
  12495. this.g = attribute.getY( index );
  12496. this.b = attribute.getZ( index );
  12497. return this;
  12498. }
  12499. /**
  12500. * This methods defines the serialization result of this class. Returns the color
  12501. * as a hexadecimal value.
  12502. *
  12503. * @return {number} The hexadecimal value.
  12504. */
  12505. toJSON() {
  12506. return this.getHex();
  12507. }
  12508. *[ Symbol.iterator ]() {
  12509. yield this.r;
  12510. yield this.g;
  12511. yield this.b;
  12512. }
  12513. }
  12514. const _color = /*@__PURE__*/ new Color();
  12515. /**
  12516. * A dictionary with X11 color names.
  12517. *
  12518. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12519. *
  12520. * @static
  12521. * @type {Object}
  12522. */
  12523. Color.NAMES = _colorKeywords;
  12524. let _materialId = 0;
  12525. /**
  12526. * Abstract base class for materials.
  12527. *
  12528. * Materials define the appearance of renderable 3D objects.
  12529. *
  12530. * @abstract
  12531. * @augments EventDispatcher
  12532. */
  12533. class Material extends EventDispatcher {
  12534. /**
  12535. * Constructs a new material.
  12536. */
  12537. constructor() {
  12538. super();
  12539. /**
  12540. * This flag can be used for type testing.
  12541. *
  12542. * @type {boolean}
  12543. * @readonly
  12544. * @default true
  12545. */
  12546. this.isMaterial = true;
  12547. /**
  12548. * The ID of the material.
  12549. *
  12550. * @name Material#id
  12551. * @type {number}
  12552. * @readonly
  12553. */
  12554. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12555. /**
  12556. * The UUID of the material.
  12557. *
  12558. * @type {string}
  12559. * @readonly
  12560. */
  12561. this.uuid = generateUUID();
  12562. /**
  12563. * The name of the material.
  12564. *
  12565. * @type {string}
  12566. */
  12567. this.name = '';
  12568. /**
  12569. * The type property is used for detecting the object type
  12570. * in context of serialization/deserialization.
  12571. *
  12572. * @type {string}
  12573. * @readonly
  12574. */
  12575. this.type = 'Material';
  12576. /**
  12577. * Defines the blending type of the material.
  12578. *
  12579. * It must be set to `CustomBlending` if custom blending properties like
  12580. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12581. * should have any effect.
  12582. *
  12583. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12584. * @default NormalBlending
  12585. */
  12586. this.blending = NormalBlending;
  12587. /**
  12588. * Defines which side of faces will be rendered - front, back or both.
  12589. *
  12590. * @type {(FrontSide|BackSide|DoubleSide)}
  12591. * @default FrontSide
  12592. */
  12593. this.side = FrontSide;
  12594. /**
  12595. * If set to `true`, vertex colors should be used.
  12596. *
  12597. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12598. * four (RGBA) component color buffer attribute is used.
  12599. *
  12600. * @type {boolean}
  12601. * @default false
  12602. */
  12603. this.vertexColors = false;
  12604. /**
  12605. * Defines how transparent the material is.
  12606. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12607. *
  12608. * If the {@link Material#transparent} is not set to `true`,
  12609. * the material will remain fully opaque and this value will only affect its color.
  12610. *
  12611. * @type {number}
  12612. * @default 1
  12613. */
  12614. this.opacity = 1;
  12615. /**
  12616. * Defines whether this material is transparent. This has an effect on
  12617. * rendering as transparent objects need special treatment and are rendered
  12618. * after non-transparent objects.
  12619. *
  12620. * When set to true, the extent to which the material is transparent is
  12621. * controlled by {@link Material#opacity}.
  12622. *
  12623. * @type {boolean}
  12624. * @default false
  12625. */
  12626. this.transparent = false;
  12627. /**
  12628. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12629. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12630. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12631. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12632. *
  12633. * @type {boolean}
  12634. * @default false
  12635. */
  12636. this.alphaHash = false;
  12637. /**
  12638. * Defines the blending source factor.
  12639. *
  12640. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12641. * @default SrcAlphaFactor
  12642. */
  12643. this.blendSrc = SrcAlphaFactor;
  12644. /**
  12645. * Defines the blending destination factor.
  12646. *
  12647. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12648. * @default OneMinusSrcAlphaFactor
  12649. */
  12650. this.blendDst = OneMinusSrcAlphaFactor;
  12651. /**
  12652. * Defines the blending equation.
  12653. *
  12654. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12655. * @default AddEquation
  12656. */
  12657. this.blendEquation = AddEquation;
  12658. /**
  12659. * Defines the blending source alpha factor.
  12660. *
  12661. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12662. * @default null
  12663. */
  12664. this.blendSrcAlpha = null;
  12665. /**
  12666. * Defines the blending destination alpha factor.
  12667. *
  12668. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12669. * @default null
  12670. */
  12671. this.blendDstAlpha = null;
  12672. /**
  12673. * Defines the blending equation of the alpha channel.
  12674. *
  12675. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12676. * @default null
  12677. */
  12678. this.blendEquationAlpha = null;
  12679. /**
  12680. * Represents the RGB values of the constant blend color.
  12681. *
  12682. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12683. *
  12684. * @type {Color}
  12685. * @default (0,0,0)
  12686. */
  12687. this.blendColor = new Color( 0, 0, 0 );
  12688. /**
  12689. * Represents the alpha value of the constant blend color.
  12690. *
  12691. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12692. *
  12693. * @type {number}
  12694. * @default 0
  12695. */
  12696. this.blendAlpha = 0;
  12697. /**
  12698. * Defines the depth function.
  12699. *
  12700. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12701. * @default LessEqualDepth
  12702. */
  12703. this.depthFunc = LessEqualDepth;
  12704. /**
  12705. * Whether to have depth test enabled when rendering this material.
  12706. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12707. *
  12708. * @type {boolean}
  12709. * @default true
  12710. */
  12711. this.depthTest = true;
  12712. /**
  12713. * Whether rendering this material has any effect on the depth buffer.
  12714. *
  12715. * When drawing 2D overlays it can be useful to disable the depth writing in
  12716. * order to layer several things together without creating z-index artifacts.
  12717. *
  12718. * @type {boolean}
  12719. * @default true
  12720. */
  12721. this.depthWrite = true;
  12722. /**
  12723. * The bit mask to use when writing to the stencil buffer.
  12724. *
  12725. * @type {number}
  12726. * @default 0xff
  12727. */
  12728. this.stencilWriteMask = 0xff;
  12729. /**
  12730. * The stencil comparison function to use.
  12731. *
  12732. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12733. * @default AlwaysStencilFunc
  12734. */
  12735. this.stencilFunc = AlwaysStencilFunc;
  12736. /**
  12737. * The value to use when performing stencil comparisons or stencil operations.
  12738. *
  12739. * @type {number}
  12740. * @default 0
  12741. */
  12742. this.stencilRef = 0;
  12743. /**
  12744. * The bit mask to use when comparing against the stencil buffer.
  12745. *
  12746. * @type {number}
  12747. * @default 0xff
  12748. */
  12749. this.stencilFuncMask = 0xff;
  12750. /**
  12751. * Which stencil operation to perform when the comparison function returns `false`.
  12752. *
  12753. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12754. * @default KeepStencilOp
  12755. */
  12756. this.stencilFail = KeepStencilOp;
  12757. /**
  12758. * Which stencil operation to perform when the comparison function returns
  12759. * `true` but the depth test fails.
  12760. *
  12761. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12762. * @default KeepStencilOp
  12763. */
  12764. this.stencilZFail = KeepStencilOp;
  12765. /**
  12766. * Which stencil operation to perform when the comparison function returns
  12767. * `true` and the depth test passes.
  12768. *
  12769. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12770. * @default KeepStencilOp
  12771. */
  12772. this.stencilZPass = KeepStencilOp;
  12773. /**
  12774. * Whether stencil operations are performed against the stencil buffer. In
  12775. * order to perform writes or comparisons against the stencil buffer this
  12776. * value must be `true`.
  12777. *
  12778. * @type {boolean}
  12779. * @default false
  12780. */
  12781. this.stencilWrite = false;
  12782. /**
  12783. * User-defined clipping planes specified as THREE.Plane objects in world
  12784. * space. These planes apply to the objects this material is attached to.
  12785. * Points in space whose signed distance to the plane is negative are clipped
  12786. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12787. * be `true`.
  12788. *
  12789. * @type {?Array<Plane>}
  12790. * @default null
  12791. */
  12792. this.clippingPlanes = null;
  12793. /**
  12794. * Changes the behavior of clipping planes so that only their intersection is
  12795. * clipped, rather than their union.
  12796. *
  12797. * @type {boolean}
  12798. * @default false
  12799. */
  12800. this.clipIntersection = false;
  12801. /**
  12802. * Defines whether to clip shadows according to the clipping planes specified
  12803. * on this material.
  12804. *
  12805. * @type {boolean}
  12806. * @default false
  12807. */
  12808. this.clipShadows = false;
  12809. /**
  12810. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12811. * is determined as follows:
  12812. *
  12813. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12814. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12815. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12816. *
  12817. * @type {?(FrontSide|BackSide|DoubleSide)}
  12818. * @default null
  12819. */
  12820. this.shadowSide = null;
  12821. /**
  12822. * Whether to render the material's color.
  12823. *
  12824. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12825. * objects that occlude other objects.
  12826. *
  12827. * @type {boolean}
  12828. * @default true
  12829. */
  12830. this.colorWrite = true;
  12831. /**
  12832. * Override the renderer's default precision for this material.
  12833. *
  12834. * @type {?('highp'|'mediump'|'lowp')}
  12835. * @default null
  12836. */
  12837. this.precision = null;
  12838. /**
  12839. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12840. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12841. * The offset is added before the depth test is performed and before the value is written
  12842. * into the depth buffer.
  12843. *
  12844. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12845. * rendering solids with highlighted edges.
  12846. *
  12847. * @type {boolean}
  12848. * @default false
  12849. */
  12850. this.polygonOffset = false;
  12851. /**
  12852. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12853. *
  12854. * @type {number}
  12855. * @default 0
  12856. */
  12857. this.polygonOffsetFactor = 0;
  12858. /**
  12859. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12860. *
  12861. * @type {number}
  12862. * @default 0
  12863. */
  12864. this.polygonOffsetUnits = 0;
  12865. /**
  12866. * Whether to apply dithering to the color to remove the appearance of banding.
  12867. *
  12868. * @type {boolean}
  12869. * @default false
  12870. */
  12871. this.dithering = false;
  12872. /**
  12873. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12874. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12875. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12876. *
  12877. * @type {boolean}
  12878. * @default false
  12879. */
  12880. this.alphaToCoverage = false;
  12881. /**
  12882. * Whether to premultiply the alpha (transparency) value.
  12883. *
  12884. * @type {boolean}
  12885. * @default false
  12886. */
  12887. this.premultipliedAlpha = false;
  12888. /**
  12889. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12890. *
  12891. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12892. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12893. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12894. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12895. * disable the two pass rendering to avoid performance issues.
  12896. *
  12897. * @type {boolean}
  12898. * @default false
  12899. */
  12900. this.forceSinglePass = false;
  12901. /**
  12902. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12903. *
  12904. * @type {boolean}
  12905. * @default true
  12906. */
  12907. this.allowOverride = true;
  12908. /**
  12909. * Defines whether 3D objects using this material are visible.
  12910. *
  12911. * @type {boolean}
  12912. * @default true
  12913. */
  12914. this.visible = true;
  12915. /**
  12916. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12917. *
  12918. * It is ignored when rendering to a render target or using post processing or when using
  12919. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12920. *
  12921. * @type {boolean}
  12922. * @default true
  12923. */
  12924. this.toneMapped = true;
  12925. /**
  12926. * An object that can be used to store custom data about the Material. It
  12927. * should not hold references to functions as these will not be cloned.
  12928. *
  12929. * @type {Object}
  12930. */
  12931. this.userData = {};
  12932. /**
  12933. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12934. *
  12935. * @type {number}
  12936. * @readonly
  12937. * @default 0
  12938. */
  12939. this.version = 0;
  12940. this._alphaTest = 0;
  12941. }
  12942. /**
  12943. * Sets the alpha value to be used when running an alpha test. The material
  12944. * will not be rendered if the opacity is lower than this value.
  12945. *
  12946. * @type {number}
  12947. * @readonly
  12948. * @default 0
  12949. */
  12950. get alphaTest() {
  12951. return this._alphaTest;
  12952. }
  12953. set alphaTest( value ) {
  12954. if ( this._alphaTest > 0 !== value > 0 ) {
  12955. this.version ++;
  12956. }
  12957. this._alphaTest = value;
  12958. }
  12959. /**
  12960. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12961. *
  12962. * This method can only be used when rendering with {@link WebGLRenderer}.
  12963. *
  12964. * @param {WebGLRenderer} renderer - The renderer.
  12965. * @param {Scene} scene - The scene.
  12966. * @param {Camera} camera - The camera that is used to render the scene.
  12967. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12968. * @param {Object3D} object - The 3D object.
  12969. * @param {Object} group - The geometry group data.
  12970. */
  12971. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12972. /**
  12973. * An optional callback that is executed immediately before the shader
  12974. * program is compiled. This function is called with the shader source code
  12975. * as a parameter. Useful for the modification of built-in materials.
  12976. *
  12977. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12978. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12979. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  12980. *
  12981. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12982. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12983. */
  12984. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12985. /**
  12986. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12987. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12988. * shader or recompile the shader for this material as needed.
  12989. *
  12990. * This method can only be used when rendering with {@link WebGLRenderer}.
  12991. *
  12992. * @return {string} The custom program cache key.
  12993. */
  12994. customProgramCacheKey() {
  12995. return this.onBeforeCompile.toString();
  12996. }
  12997. /**
  12998. * This method can be used to set default values from parameter objects.
  12999. * It is a generic implementation so it can be used with different types
  13000. * of materials.
  13001. *
  13002. * @param {Object} [values] - The material values to set.
  13003. */
  13004. setValues( values ) {
  13005. if ( values === undefined ) return;
  13006. for ( const key in values ) {
  13007. const newValue = values[ key ];
  13008. if ( newValue === undefined ) {
  13009. warn( `Material: parameter '${ key }' has value of undefined.` );
  13010. continue;
  13011. }
  13012. const currentValue = this[ key ];
  13013. if ( currentValue === undefined ) {
  13014. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  13015. continue;
  13016. }
  13017. if ( currentValue && currentValue.isColor ) {
  13018. currentValue.set( newValue );
  13019. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  13020. currentValue.copy( newValue );
  13021. } else {
  13022. this[ key ] = newValue;
  13023. }
  13024. }
  13025. }
  13026. /**
  13027. * Serializes the material into JSON.
  13028. *
  13029. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  13030. * @return {Object} A JSON object representing the serialized material.
  13031. * @see {@link ObjectLoader#parse}
  13032. */
  13033. toJSON( meta ) {
  13034. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  13035. if ( isRootObject ) {
  13036. meta = {
  13037. textures: {},
  13038. images: {}
  13039. };
  13040. }
  13041. const data = {
  13042. metadata: {
  13043. version: 4.7,
  13044. type: 'Material',
  13045. generator: 'Material.toJSON'
  13046. }
  13047. };
  13048. // standard Material serialization
  13049. data.uuid = this.uuid;
  13050. data.type = this.type;
  13051. if ( this.name !== '' ) data.name = this.name;
  13052. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  13053. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  13054. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  13055. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  13056. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  13057. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  13058. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  13059. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  13060. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  13061. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  13062. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  13063. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  13064. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  13065. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  13066. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  13067. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  13068. }
  13069. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  13070. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  13071. }
  13072. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  13073. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  13074. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  13075. }
  13076. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  13077. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  13078. }
  13079. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  13080. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  13081. }
  13082. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  13083. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  13084. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  13085. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  13086. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  13087. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  13088. }
  13089. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  13090. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  13091. }
  13092. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  13093. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  13094. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  13095. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  13096. }
  13097. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  13098. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  13099. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  13100. if ( this.lightMap && this.lightMap.isTexture ) {
  13101. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  13102. data.lightMapIntensity = this.lightMapIntensity;
  13103. }
  13104. if ( this.aoMap && this.aoMap.isTexture ) {
  13105. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  13106. data.aoMapIntensity = this.aoMapIntensity;
  13107. }
  13108. if ( this.bumpMap && this.bumpMap.isTexture ) {
  13109. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  13110. data.bumpScale = this.bumpScale;
  13111. }
  13112. if ( this.normalMap && this.normalMap.isTexture ) {
  13113. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  13114. data.normalMapType = this.normalMapType;
  13115. data.normalScale = this.normalScale.toArray();
  13116. }
  13117. if ( this.displacementMap && this.displacementMap.isTexture ) {
  13118. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  13119. data.displacementScale = this.displacementScale;
  13120. data.displacementBias = this.displacementBias;
  13121. }
  13122. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  13123. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  13124. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  13125. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  13126. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  13127. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  13128. if ( this.envMap && this.envMap.isTexture ) {
  13129. data.envMap = this.envMap.toJSON( meta ).uuid;
  13130. if ( this.combine !== undefined ) data.combine = this.combine;
  13131. }
  13132. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  13133. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  13134. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  13135. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  13136. if ( this.gradientMap && this.gradientMap.isTexture ) {
  13137. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  13138. }
  13139. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  13140. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  13141. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  13142. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  13143. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  13144. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  13145. if ( this.size !== undefined ) data.size = this.size;
  13146. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  13147. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  13148. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  13149. if ( this.side !== FrontSide ) data.side = this.side;
  13150. if ( this.vertexColors === true ) data.vertexColors = true;
  13151. if ( this.opacity < 1 ) data.opacity = this.opacity;
  13152. if ( this.transparent === true ) data.transparent = true;
  13153. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  13154. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  13155. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  13156. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  13157. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  13158. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  13159. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  13160. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  13161. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  13162. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  13163. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  13164. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  13165. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  13166. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  13167. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  13168. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  13169. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  13170. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  13171. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  13172. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  13173. // rotation (SpriteMaterial)
  13174. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  13175. if ( this.polygonOffset === true ) data.polygonOffset = true;
  13176. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  13177. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  13178. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  13179. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  13180. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  13181. if ( this.scale !== undefined ) data.scale = this.scale;
  13182. if ( this.dithering === true ) data.dithering = true;
  13183. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  13184. if ( this.alphaHash === true ) data.alphaHash = true;
  13185. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  13186. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  13187. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  13188. if ( this.allowOverride === false ) data.allowOverride = false;
  13189. if ( this.wireframe === true ) data.wireframe = true;
  13190. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  13191. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  13192. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  13193. if ( this.flatShading === true ) data.flatShading = true;
  13194. if ( this.visible === false ) data.visible = false;
  13195. if ( this.toneMapped === false ) data.toneMapped = false;
  13196. if ( this.fog === false ) data.fog = false;
  13197. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  13198. // TODO: Copied from Object3D.toJSON
  13199. function extractFromCache( cache ) {
  13200. const values = [];
  13201. for ( const key in cache ) {
  13202. const data = cache[ key ];
  13203. delete data.metadata;
  13204. values.push( data );
  13205. }
  13206. return values;
  13207. }
  13208. if ( isRootObject ) {
  13209. const textures = extractFromCache( meta.textures );
  13210. const images = extractFromCache( meta.images );
  13211. if ( textures.length > 0 ) data.textures = textures;
  13212. if ( images.length > 0 ) data.images = images;
  13213. }
  13214. return data;
  13215. }
  13216. /**
  13217. * Returns a new material with copied values from this instance.
  13218. *
  13219. * @return {Material} A clone of this instance.
  13220. */
  13221. clone() {
  13222. return new this.constructor().copy( this );
  13223. }
  13224. /**
  13225. * Copies the values of the given material to this instance.
  13226. *
  13227. * @param {Material} source - The material to copy.
  13228. * @return {Material} A reference to this instance.
  13229. */
  13230. copy( source ) {
  13231. this.name = source.name;
  13232. this.blending = source.blending;
  13233. this.side = source.side;
  13234. this.vertexColors = source.vertexColors;
  13235. this.opacity = source.opacity;
  13236. this.transparent = source.transparent;
  13237. this.blendSrc = source.blendSrc;
  13238. this.blendDst = source.blendDst;
  13239. this.blendEquation = source.blendEquation;
  13240. this.blendSrcAlpha = source.blendSrcAlpha;
  13241. this.blendDstAlpha = source.blendDstAlpha;
  13242. this.blendEquationAlpha = source.blendEquationAlpha;
  13243. this.blendColor.copy( source.blendColor );
  13244. this.blendAlpha = source.blendAlpha;
  13245. this.depthFunc = source.depthFunc;
  13246. this.depthTest = source.depthTest;
  13247. this.depthWrite = source.depthWrite;
  13248. this.stencilWriteMask = source.stencilWriteMask;
  13249. this.stencilFunc = source.stencilFunc;
  13250. this.stencilRef = source.stencilRef;
  13251. this.stencilFuncMask = source.stencilFuncMask;
  13252. this.stencilFail = source.stencilFail;
  13253. this.stencilZFail = source.stencilZFail;
  13254. this.stencilZPass = source.stencilZPass;
  13255. this.stencilWrite = source.stencilWrite;
  13256. const srcPlanes = source.clippingPlanes;
  13257. let dstPlanes = null;
  13258. if ( srcPlanes !== null ) {
  13259. const n = srcPlanes.length;
  13260. dstPlanes = new Array( n );
  13261. for ( let i = 0; i !== n; ++ i ) {
  13262. dstPlanes[ i ] = srcPlanes[ i ].clone();
  13263. }
  13264. }
  13265. this.clippingPlanes = dstPlanes;
  13266. this.clipIntersection = source.clipIntersection;
  13267. this.clipShadows = source.clipShadows;
  13268. this.shadowSide = source.shadowSide;
  13269. this.colorWrite = source.colorWrite;
  13270. this.precision = source.precision;
  13271. this.polygonOffset = source.polygonOffset;
  13272. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13273. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13274. this.dithering = source.dithering;
  13275. this.alphaTest = source.alphaTest;
  13276. this.alphaHash = source.alphaHash;
  13277. this.alphaToCoverage = source.alphaToCoverage;
  13278. this.premultipliedAlpha = source.premultipliedAlpha;
  13279. this.forceSinglePass = source.forceSinglePass;
  13280. this.allowOverride = source.allowOverride;
  13281. this.visible = source.visible;
  13282. this.toneMapped = source.toneMapped;
  13283. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13284. return this;
  13285. }
  13286. /**
  13287. * Frees the GPU-related resources allocated by this instance. Call this
  13288. * method whenever this instance is no longer used in your app.
  13289. *
  13290. * @fires Material#dispose
  13291. */
  13292. dispose() {
  13293. /**
  13294. * Fires when the material has been disposed of.
  13295. *
  13296. * @event Material#dispose
  13297. * @type {Object}
  13298. */
  13299. this.dispatchEvent( { type: 'dispose' } );
  13300. }
  13301. /**
  13302. * Setting this property to `true` indicates the engine the material
  13303. * needs to be recompiled.
  13304. *
  13305. * @type {boolean}
  13306. * @default false
  13307. * @param {boolean} value
  13308. */
  13309. set needsUpdate( value ) {
  13310. if ( value === true ) this.version ++;
  13311. }
  13312. }
  13313. /**
  13314. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13315. *
  13316. * This material is not affected by lights.
  13317. *
  13318. * @augments Material
  13319. * @demo scenes/material-browser.html#MeshBasicMaterial
  13320. */
  13321. class MeshBasicMaterial extends Material {
  13322. /**
  13323. * Constructs a new mesh basic material.
  13324. *
  13325. * @param {Object} [parameters] - An object with one or more properties
  13326. * defining the material's appearance. Any property of the material
  13327. * (including any property from inherited materials) can be passed
  13328. * in here. Color values can be passed any type of value accepted
  13329. * by {@link Color#set}.
  13330. */
  13331. constructor( parameters ) {
  13332. super();
  13333. /**
  13334. * This flag can be used for type testing.
  13335. *
  13336. * @type {boolean}
  13337. * @readonly
  13338. * @default true
  13339. */
  13340. this.isMeshBasicMaterial = true;
  13341. this.type = 'MeshBasicMaterial';
  13342. /**
  13343. * Color of the material.
  13344. *
  13345. * @type {Color}
  13346. * @default (1,1,1)
  13347. */
  13348. this.color = new Color( 0xffffff ); // diffuse
  13349. /**
  13350. * The color map. May optionally include an alpha channel, typically combined
  13351. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13352. * color is modulated by the diffuse `color`.
  13353. *
  13354. * @type {?Texture}
  13355. * @default null
  13356. */
  13357. this.map = null;
  13358. /**
  13359. * The light map. Requires a second set of UVs.
  13360. *
  13361. * @type {?Texture}
  13362. * @default null
  13363. */
  13364. this.lightMap = null;
  13365. /**
  13366. * Intensity of the baked light.
  13367. *
  13368. * @type {number}
  13369. * @default 1
  13370. */
  13371. this.lightMapIntensity = 1.0;
  13372. /**
  13373. * The red channel of this texture is used as the ambient occlusion map.
  13374. * Requires a second set of UVs.
  13375. *
  13376. * @type {?Texture}
  13377. * @default null
  13378. */
  13379. this.aoMap = null;
  13380. /**
  13381. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13382. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13383. * red channel is also `1`, ambient light is fully occluded on a surface.
  13384. *
  13385. * @type {number}
  13386. * @default 1
  13387. */
  13388. this.aoMapIntensity = 1.0;
  13389. /**
  13390. * Specular map used by the material.
  13391. *
  13392. * @type {?Texture}
  13393. * @default null
  13394. */
  13395. this.specularMap = null;
  13396. /**
  13397. * The alpha map is a grayscale texture that controls the opacity across the
  13398. * surface (black: fully transparent; white: fully opaque).
  13399. *
  13400. * Only the color of the texture is used, ignoring the alpha channel if one
  13401. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13402. * when sampling this texture due to the extra bit of precision provided for
  13403. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13404. * luminance/alpha textures will also still work as expected.
  13405. *
  13406. * @type {?Texture}
  13407. * @default null
  13408. */
  13409. this.alphaMap = null;
  13410. /**
  13411. * The environment map.
  13412. *
  13413. * @type {?Texture}
  13414. * @default null
  13415. */
  13416. this.envMap = null;
  13417. /**
  13418. * The rotation of the environment map in radians.
  13419. *
  13420. * @type {Euler}
  13421. * @default (0,0,0)
  13422. */
  13423. this.envMapRotation = new Euler();
  13424. /**
  13425. * How to combine the result of the surface's color with the environment map, if any.
  13426. *
  13427. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13428. * blend between the two colors.
  13429. *
  13430. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13431. * @default MultiplyOperation
  13432. */
  13433. this.combine = MultiplyOperation;
  13434. /**
  13435. * How much the environment map affects the surface.
  13436. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13437. *
  13438. * @type {number}
  13439. * @default 1
  13440. */
  13441. this.reflectivity = 1;
  13442. /**
  13443. * The index of refraction (IOR) of air (approximately 1) divided by the
  13444. * index of refraction of the material. It is used with environment mapping
  13445. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13446. * The refraction ratio should not exceed `1`.
  13447. *
  13448. * @type {number}
  13449. * @default 0.98
  13450. */
  13451. this.refractionRatio = 0.98;
  13452. /**
  13453. * Renders the geometry as a wireframe.
  13454. *
  13455. * @type {boolean}
  13456. * @default false
  13457. */
  13458. this.wireframe = false;
  13459. /**
  13460. * Controls the thickness of the wireframe.
  13461. *
  13462. * Can only be used with {@link SVGRenderer}.
  13463. *
  13464. * @type {number}
  13465. * @default 1
  13466. */
  13467. this.wireframeLinewidth = 1;
  13468. /**
  13469. * Defines appearance of wireframe ends.
  13470. *
  13471. * Can only be used with {@link SVGRenderer}.
  13472. *
  13473. * @type {('round'|'bevel'|'miter')}
  13474. * @default 'round'
  13475. */
  13476. this.wireframeLinecap = 'round';
  13477. /**
  13478. * Defines appearance of wireframe joints.
  13479. *
  13480. * Can only be used with {@link SVGRenderer}.
  13481. *
  13482. * @type {('round'|'bevel'|'miter')}
  13483. * @default 'round'
  13484. */
  13485. this.wireframeLinejoin = 'round';
  13486. /**
  13487. * Whether the material is affected by fog or not.
  13488. *
  13489. * @type {boolean}
  13490. * @default true
  13491. */
  13492. this.fog = true;
  13493. this.setValues( parameters );
  13494. }
  13495. copy( source ) {
  13496. super.copy( source );
  13497. this.color.copy( source.color );
  13498. this.map = source.map;
  13499. this.lightMap = source.lightMap;
  13500. this.lightMapIntensity = source.lightMapIntensity;
  13501. this.aoMap = source.aoMap;
  13502. this.aoMapIntensity = source.aoMapIntensity;
  13503. this.specularMap = source.specularMap;
  13504. this.alphaMap = source.alphaMap;
  13505. this.envMap = source.envMap;
  13506. this.envMapRotation.copy( source.envMapRotation );
  13507. this.combine = source.combine;
  13508. this.reflectivity = source.reflectivity;
  13509. this.refractionRatio = source.refractionRatio;
  13510. this.wireframe = source.wireframe;
  13511. this.wireframeLinewidth = source.wireframeLinewidth;
  13512. this.wireframeLinecap = source.wireframeLinecap;
  13513. this.wireframeLinejoin = source.wireframeLinejoin;
  13514. this.fog = source.fog;
  13515. return this;
  13516. }
  13517. }
  13518. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13519. const _tables = /*@__PURE__*/ _generateTables();
  13520. function _generateTables() {
  13521. // float32 to float16 helpers
  13522. const buffer = new ArrayBuffer( 4 );
  13523. const floatView = new Float32Array( buffer );
  13524. const uint32View = new Uint32Array( buffer );
  13525. const baseTable = new Uint32Array( 512 );
  13526. const shiftTable = new Uint32Array( 512 );
  13527. for ( let i = 0; i < 256; ++ i ) {
  13528. const e = i - 127;
  13529. // very small number (0, -0)
  13530. if ( e < -27 ) {
  13531. baseTable[ i ] = 0x0000;
  13532. baseTable[ i | 0x100 ] = 0x8000;
  13533. shiftTable[ i ] = 24;
  13534. shiftTable[ i | 0x100 ] = 24;
  13535. // small number (denorm)
  13536. } else if ( e < -14 ) {
  13537. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13538. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13539. shiftTable[ i ] = - e - 1;
  13540. shiftTable[ i | 0x100 ] = - e - 1;
  13541. // normal number
  13542. } else if ( e <= 15 ) {
  13543. baseTable[ i ] = ( e + 15 ) << 10;
  13544. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13545. shiftTable[ i ] = 13;
  13546. shiftTable[ i | 0x100 ] = 13;
  13547. // large number (Infinity, -Infinity)
  13548. } else if ( e < 128 ) {
  13549. baseTable[ i ] = 0x7c00;
  13550. baseTable[ i | 0x100 ] = 0xfc00;
  13551. shiftTable[ i ] = 24;
  13552. shiftTable[ i | 0x100 ] = 24;
  13553. // stay (NaN, Infinity, -Infinity)
  13554. } else {
  13555. baseTable[ i ] = 0x7c00;
  13556. baseTable[ i | 0x100 ] = 0xfc00;
  13557. shiftTable[ i ] = 13;
  13558. shiftTable[ i | 0x100 ] = 13;
  13559. }
  13560. }
  13561. // float16 to float32 helpers
  13562. const mantissaTable = new Uint32Array( 2048 );
  13563. const exponentTable = new Uint32Array( 64 );
  13564. const offsetTable = new Uint32Array( 64 );
  13565. for ( let i = 1; i < 1024; ++ i ) {
  13566. let m = i << 13; // zero pad mantissa bits
  13567. let e = 0; // zero exponent
  13568. // normalized
  13569. while ( ( m & 0x00800000 ) === 0 ) {
  13570. m <<= 1;
  13571. e -= 0x00800000; // decrement exponent
  13572. }
  13573. m &= -8388609; // clear leading 1 bit
  13574. e += 0x38800000; // adjust bias
  13575. mantissaTable[ i ] = m | e;
  13576. }
  13577. for ( let i = 1024; i < 2048; ++ i ) {
  13578. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13579. }
  13580. for ( let i = 1; i < 31; ++ i ) {
  13581. exponentTable[ i ] = i << 23;
  13582. }
  13583. exponentTable[ 31 ] = 0x47800000;
  13584. exponentTable[ 32 ] = 0x80000000;
  13585. for ( let i = 33; i < 63; ++ i ) {
  13586. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13587. }
  13588. exponentTable[ 63 ] = 0xc7800000;
  13589. for ( let i = 1; i < 64; ++ i ) {
  13590. if ( i !== 32 ) {
  13591. offsetTable[ i ] = 1024;
  13592. }
  13593. }
  13594. return {
  13595. floatView: floatView,
  13596. uint32View: uint32View,
  13597. baseTable: baseTable,
  13598. shiftTable: shiftTable,
  13599. mantissaTable: mantissaTable,
  13600. exponentTable: exponentTable,
  13601. offsetTable: offsetTable
  13602. };
  13603. }
  13604. /**
  13605. * Returns a half precision floating point value (FP16) from the given single
  13606. * precision floating point value (FP32).
  13607. *
  13608. * @param {number} val - A single precision floating point value.
  13609. * @return {number} The FP16 value.
  13610. */
  13611. function toHalfFloat( val ) {
  13612. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  13613. val = clamp( val, -65504, 65504 );
  13614. _tables.floatView[ 0 ] = val;
  13615. const f = _tables.uint32View[ 0 ];
  13616. const e = ( f >> 23 ) & 0x1ff;
  13617. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13618. }
  13619. /**
  13620. * Returns a single precision floating point value (FP32) from the given half
  13621. * precision floating point value (FP16).
  13622. *
  13623. * @param {number} val - A half precision floating point value.
  13624. * @return {number} The FP32 value.
  13625. */
  13626. function fromHalfFloat( val ) {
  13627. const m = val >> 10;
  13628. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13629. return _tables.floatView[ 0 ];
  13630. }
  13631. /**
  13632. * A class containing utility functions for data.
  13633. *
  13634. * @hideconstructor
  13635. */
  13636. class DataUtils {
  13637. /**
  13638. * Returns a half precision floating point value (FP16) from the given single
  13639. * precision floating point value (FP32).
  13640. *
  13641. * @param {number} val - A single precision floating point value.
  13642. * @return {number} The FP16 value.
  13643. */
  13644. static toHalfFloat( val ) {
  13645. return toHalfFloat( val );
  13646. }
  13647. /**
  13648. * Returns a single precision floating point value (FP32) from the given half
  13649. * precision floating point value (FP16).
  13650. *
  13651. * @param {number} val - A half precision floating point value.
  13652. * @return {number} The FP32 value.
  13653. */
  13654. static fromHalfFloat( val ) {
  13655. return fromHalfFloat( val );
  13656. }
  13657. }
  13658. const _vector$9 = /*@__PURE__*/ new Vector3();
  13659. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13660. let _id$2 = 0;
  13661. /**
  13662. * This class stores data for an attribute (such as vertex positions, face
  13663. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13664. * a geometry, which allows for more efficient passing of data to the GPU.
  13665. *
  13666. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13667. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13668. */
  13669. class BufferAttribute {
  13670. /**
  13671. * Constructs a new buffer attribute.
  13672. *
  13673. * @param {TypedArray} array - The array holding the attribute data.
  13674. * @param {number} itemSize - The item size.
  13675. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13676. */
  13677. constructor( array, itemSize, normalized = false ) {
  13678. if ( Array.isArray( array ) ) {
  13679. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13680. }
  13681. /**
  13682. * This flag can be used for type testing.
  13683. *
  13684. * @type {boolean}
  13685. * @readonly
  13686. * @default true
  13687. */
  13688. this.isBufferAttribute = true;
  13689. /**
  13690. * The ID of the buffer attribute.
  13691. *
  13692. * @name BufferAttribute#id
  13693. * @type {number}
  13694. * @readonly
  13695. */
  13696. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  13697. /**
  13698. * The name of the buffer attribute.
  13699. *
  13700. * @type {string}
  13701. */
  13702. this.name = '';
  13703. /**
  13704. * The array holding the attribute data. It should have `itemSize * numVertices`
  13705. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13706. *
  13707. * @type {TypedArray}
  13708. */
  13709. this.array = array;
  13710. /**
  13711. * The number of values of the array that should be associated with a particular vertex.
  13712. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13713. * normal, or color), then the value should be `3`.
  13714. *
  13715. * @type {number}
  13716. */
  13717. this.itemSize = itemSize;
  13718. /**
  13719. * Represents the number of items this buffer attribute stores. It is internally computed
  13720. * by dividing the `array` length by the `itemSize`.
  13721. *
  13722. * @type {number}
  13723. * @readonly
  13724. */
  13725. this.count = array !== undefined ? array.length / itemSize : 0;
  13726. /**
  13727. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13728. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13729. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13730. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13731. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13732. *
  13733. * @type {boolean}
  13734. */
  13735. this.normalized = normalized;
  13736. /**
  13737. * Defines the intended usage pattern of the data store for optimization purposes.
  13738. *
  13739. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13740. * instantiate a new one and set the desired usage before the next render.
  13741. *
  13742. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13743. * @default StaticDrawUsage
  13744. */
  13745. this.usage = StaticDrawUsage;
  13746. /**
  13747. * This can be used to only update some components of stored vectors (for example, just the
  13748. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13749. *
  13750. * @type {Array<Object>}
  13751. */
  13752. this.updateRanges = [];
  13753. /**
  13754. * Configures the bound GPU type for use in shaders.
  13755. *
  13756. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13757. * For lower precision float types, use `Float16BufferAttribute`.
  13758. *
  13759. * @type {(FloatType|IntType)}
  13760. * @default FloatType
  13761. */
  13762. this.gpuType = FloatType;
  13763. /**
  13764. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13765. *
  13766. * @type {number}
  13767. */
  13768. this.version = 0;
  13769. }
  13770. /**
  13771. * A callback function that is executed after the renderer has transferred the attribute
  13772. * array data to the GPU.
  13773. */
  13774. onUploadCallback() {}
  13775. /**
  13776. * Flag to indicate that this attribute has changed and should be re-sent to
  13777. * the GPU. Set this to `true` when you modify the value of the array.
  13778. *
  13779. * @type {number}
  13780. * @default false
  13781. * @param {boolean} value
  13782. */
  13783. set needsUpdate( value ) {
  13784. if ( value === true ) this.version ++;
  13785. }
  13786. /**
  13787. * Sets the usage of this buffer attribute.
  13788. *
  13789. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13790. * @return {BufferAttribute} A reference to this buffer attribute.
  13791. */
  13792. setUsage( value ) {
  13793. this.usage = value;
  13794. return this;
  13795. }
  13796. /**
  13797. * Adds a range of data in the data array to be updated on the GPU.
  13798. *
  13799. * @param {number} start - Position at which to start update.
  13800. * @param {number} count - The number of components to update.
  13801. */
  13802. addUpdateRange( start, count ) {
  13803. this.updateRanges.push( { start, count } );
  13804. }
  13805. /**
  13806. * Clears the update ranges.
  13807. */
  13808. clearUpdateRanges() {
  13809. this.updateRanges.length = 0;
  13810. }
  13811. /**
  13812. * Copies the values of the given buffer attribute to this instance.
  13813. *
  13814. * @param {BufferAttribute} source - The buffer attribute to copy.
  13815. * @return {BufferAttribute} A reference to this instance.
  13816. */
  13817. copy( source ) {
  13818. this.name = source.name;
  13819. this.array = new source.array.constructor( source.array );
  13820. this.itemSize = source.itemSize;
  13821. this.count = source.count;
  13822. this.normalized = source.normalized;
  13823. this.usage = source.usage;
  13824. this.gpuType = source.gpuType;
  13825. return this;
  13826. }
  13827. /**
  13828. * Copies a vector from the given buffer attribute to this one. The start
  13829. * and destination position in the attribute buffers are represented by the
  13830. * given indices.
  13831. *
  13832. * @param {number} index1 - The destination index into this buffer attribute.
  13833. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13834. * @param {number} index2 - The source index into the given buffer attribute.
  13835. * @return {BufferAttribute} A reference to this instance.
  13836. */
  13837. copyAt( index1, attribute, index2 ) {
  13838. index1 *= this.itemSize;
  13839. index2 *= attribute.itemSize;
  13840. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13841. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13842. }
  13843. return this;
  13844. }
  13845. /**
  13846. * Copies the given array data into this buffer attribute.
  13847. *
  13848. * @param {(TypedArray|Array)} array - The array to copy.
  13849. * @return {BufferAttribute} A reference to this instance.
  13850. */
  13851. copyArray( array ) {
  13852. this.array.set( array );
  13853. return this;
  13854. }
  13855. /**
  13856. * Applies the given 3x3 matrix to the given attribute. Works with
  13857. * item size `2` and `3`.
  13858. *
  13859. * @param {Matrix3} m - The matrix to apply.
  13860. * @return {BufferAttribute} A reference to this instance.
  13861. */
  13862. applyMatrix3( m ) {
  13863. if ( this.itemSize === 2 ) {
  13864. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13865. _vector2$1.fromBufferAttribute( this, i );
  13866. _vector2$1.applyMatrix3( m );
  13867. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13868. }
  13869. } else if ( this.itemSize === 3 ) {
  13870. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13871. _vector$9.fromBufferAttribute( this, i );
  13872. _vector$9.applyMatrix3( m );
  13873. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13874. }
  13875. }
  13876. return this;
  13877. }
  13878. /**
  13879. * Applies the given 4x4 matrix to the given attribute. Only works with
  13880. * item size `3`.
  13881. *
  13882. * @param {Matrix4} m - The matrix to apply.
  13883. * @return {BufferAttribute} A reference to this instance.
  13884. */
  13885. applyMatrix4( m ) {
  13886. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13887. _vector$9.fromBufferAttribute( this, i );
  13888. _vector$9.applyMatrix4( m );
  13889. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13890. }
  13891. return this;
  13892. }
  13893. /**
  13894. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13895. * item size `3`.
  13896. *
  13897. * @param {Matrix3} m - The normal matrix to apply.
  13898. * @return {BufferAttribute} A reference to this instance.
  13899. */
  13900. applyNormalMatrix( m ) {
  13901. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13902. _vector$9.fromBufferAttribute( this, i );
  13903. _vector$9.applyNormalMatrix( m );
  13904. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13905. }
  13906. return this;
  13907. }
  13908. /**
  13909. * Applies the given 4x4 matrix to the given attribute. Only works with
  13910. * item size `3` and with direction vectors.
  13911. *
  13912. * @param {Matrix4} m - The matrix to apply.
  13913. * @return {BufferAttribute} A reference to this instance.
  13914. */
  13915. transformDirection( m ) {
  13916. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13917. _vector$9.fromBufferAttribute( this, i );
  13918. _vector$9.transformDirection( m );
  13919. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13920. }
  13921. return this;
  13922. }
  13923. /**
  13924. * Sets the given array data in the buffer attribute.
  13925. *
  13926. * @param {(TypedArray|Array)} value - The array data to set.
  13927. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13928. * @return {BufferAttribute} A reference to this instance.
  13929. */
  13930. set( value, offset = 0 ) {
  13931. // Matching BufferAttribute constructor, do not normalize the array.
  13932. this.array.set( value, offset );
  13933. return this;
  13934. }
  13935. /**
  13936. * Returns the given component of the vector at the given index.
  13937. *
  13938. * @param {number} index - The index into the buffer attribute.
  13939. * @param {number} component - The component index.
  13940. * @return {number} The returned value.
  13941. */
  13942. getComponent( index, component ) {
  13943. let value = this.array[ index * this.itemSize + component ];
  13944. if ( this.normalized ) value = denormalize( value, this.array );
  13945. return value;
  13946. }
  13947. /**
  13948. * Sets the given value to the given component of the vector at the given index.
  13949. *
  13950. * @param {number} index - The index into the buffer attribute.
  13951. * @param {number} component - The component index.
  13952. * @param {number} value - The value to set.
  13953. * @return {BufferAttribute} A reference to this instance.
  13954. */
  13955. setComponent( index, component, value ) {
  13956. if ( this.normalized ) value = normalize( value, this.array );
  13957. this.array[ index * this.itemSize + component ] = value;
  13958. return this;
  13959. }
  13960. /**
  13961. * Returns the x component of the vector at the given index.
  13962. *
  13963. * @param {number} index - The index into the buffer attribute.
  13964. * @return {number} The x component.
  13965. */
  13966. getX( index ) {
  13967. let x = this.array[ index * this.itemSize ];
  13968. if ( this.normalized ) x = denormalize( x, this.array );
  13969. return x;
  13970. }
  13971. /**
  13972. * Sets the x component of the vector at the given index.
  13973. *
  13974. * @param {number} index - The index into the buffer attribute.
  13975. * @param {number} x - The value to set.
  13976. * @return {BufferAttribute} A reference to this instance.
  13977. */
  13978. setX( index, x ) {
  13979. if ( this.normalized ) x = normalize( x, this.array );
  13980. this.array[ index * this.itemSize ] = x;
  13981. return this;
  13982. }
  13983. /**
  13984. * Returns the y component of the vector at the given index.
  13985. *
  13986. * @param {number} index - The index into the buffer attribute.
  13987. * @return {number} The y component.
  13988. */
  13989. getY( index ) {
  13990. let y = this.array[ index * this.itemSize + 1 ];
  13991. if ( this.normalized ) y = denormalize( y, this.array );
  13992. return y;
  13993. }
  13994. /**
  13995. * Sets the y component of the vector at the given index.
  13996. *
  13997. * @param {number} index - The index into the buffer attribute.
  13998. * @param {number} y - The value to set.
  13999. * @return {BufferAttribute} A reference to this instance.
  14000. */
  14001. setY( index, y ) {
  14002. if ( this.normalized ) y = normalize( y, this.array );
  14003. this.array[ index * this.itemSize + 1 ] = y;
  14004. return this;
  14005. }
  14006. /**
  14007. * Returns the z component of the vector at the given index.
  14008. *
  14009. * @param {number} index - The index into the buffer attribute.
  14010. * @return {number} The z component.
  14011. */
  14012. getZ( index ) {
  14013. let z = this.array[ index * this.itemSize + 2 ];
  14014. if ( this.normalized ) z = denormalize( z, this.array );
  14015. return z;
  14016. }
  14017. /**
  14018. * Sets the z component of the vector at the given index.
  14019. *
  14020. * @param {number} index - The index into the buffer attribute.
  14021. * @param {number} z - The value to set.
  14022. * @return {BufferAttribute} A reference to this instance.
  14023. */
  14024. setZ( index, z ) {
  14025. if ( this.normalized ) z = normalize( z, this.array );
  14026. this.array[ index * this.itemSize + 2 ] = z;
  14027. return this;
  14028. }
  14029. /**
  14030. * Returns the w component of the vector at the given index.
  14031. *
  14032. * @param {number} index - The index into the buffer attribute.
  14033. * @return {number} The w component.
  14034. */
  14035. getW( index ) {
  14036. let w = this.array[ index * this.itemSize + 3 ];
  14037. if ( this.normalized ) w = denormalize( w, this.array );
  14038. return w;
  14039. }
  14040. /**
  14041. * Sets the w component of the vector at the given index.
  14042. *
  14043. * @param {number} index - The index into the buffer attribute.
  14044. * @param {number} w - The value to set.
  14045. * @return {BufferAttribute} A reference to this instance.
  14046. */
  14047. setW( index, w ) {
  14048. if ( this.normalized ) w = normalize( w, this.array );
  14049. this.array[ index * this.itemSize + 3 ] = w;
  14050. return this;
  14051. }
  14052. /**
  14053. * Sets the x and y component of the vector at the given index.
  14054. *
  14055. * @param {number} index - The index into the buffer attribute.
  14056. * @param {number} x - The value for the x component to set.
  14057. * @param {number} y - The value for the y component to set.
  14058. * @return {BufferAttribute} A reference to this instance.
  14059. */
  14060. setXY( index, x, y ) {
  14061. index *= this.itemSize;
  14062. if ( this.normalized ) {
  14063. x = normalize( x, this.array );
  14064. y = normalize( y, this.array );
  14065. }
  14066. this.array[ index + 0 ] = x;
  14067. this.array[ index + 1 ] = y;
  14068. return this;
  14069. }
  14070. /**
  14071. * Sets the x, y and z component of the vector at the given index.
  14072. *
  14073. * @param {number} index - The index into the buffer attribute.
  14074. * @param {number} x - The value for the x component to set.
  14075. * @param {number} y - The value for the y component to set.
  14076. * @param {number} z - The value for the z component to set.
  14077. * @return {BufferAttribute} A reference to this instance.
  14078. */
  14079. setXYZ( index, x, y, z ) {
  14080. index *= this.itemSize;
  14081. if ( this.normalized ) {
  14082. x = normalize( x, this.array );
  14083. y = normalize( y, this.array );
  14084. z = normalize( z, this.array );
  14085. }
  14086. this.array[ index + 0 ] = x;
  14087. this.array[ index + 1 ] = y;
  14088. this.array[ index + 2 ] = z;
  14089. return this;
  14090. }
  14091. /**
  14092. * Sets the x, y, z and w component of the vector at the given index.
  14093. *
  14094. * @param {number} index - The index into the buffer attribute.
  14095. * @param {number} x - The value for the x component to set.
  14096. * @param {number} y - The value for the y component to set.
  14097. * @param {number} z - The value for the z component to set.
  14098. * @param {number} w - The value for the w component to set.
  14099. * @return {BufferAttribute} A reference to this instance.
  14100. */
  14101. setXYZW( index, x, y, z, w ) {
  14102. index *= this.itemSize;
  14103. if ( this.normalized ) {
  14104. x = normalize( x, this.array );
  14105. y = normalize( y, this.array );
  14106. z = normalize( z, this.array );
  14107. w = normalize( w, this.array );
  14108. }
  14109. this.array[ index + 0 ] = x;
  14110. this.array[ index + 1 ] = y;
  14111. this.array[ index + 2 ] = z;
  14112. this.array[ index + 3 ] = w;
  14113. return this;
  14114. }
  14115. /**
  14116. * Sets the given callback function that is executed after the Renderer has transferred
  14117. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  14118. * the upload when attribute data are not needed anymore on the CPU side.
  14119. *
  14120. * @param {Function} callback - The `onUpload()` callback.
  14121. * @return {BufferAttribute} A reference to this instance.
  14122. */
  14123. onUpload( callback ) {
  14124. this.onUploadCallback = callback;
  14125. return this;
  14126. }
  14127. /**
  14128. * Returns a new buffer attribute with copied values from this instance.
  14129. *
  14130. * @return {BufferAttribute} A clone of this instance.
  14131. */
  14132. clone() {
  14133. return new this.constructor( this.array, this.itemSize ).copy( this );
  14134. }
  14135. /**
  14136. * Serializes the buffer attribute into JSON.
  14137. *
  14138. * @return {Object} A JSON object representing the serialized buffer attribute.
  14139. */
  14140. toJSON() {
  14141. const data = {
  14142. itemSize: this.itemSize,
  14143. type: this.array.constructor.name,
  14144. array: Array.from( this.array ),
  14145. normalized: this.normalized
  14146. };
  14147. if ( this.name !== '' ) data.name = this.name;
  14148. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  14149. return data;
  14150. }
  14151. }
  14152. /**
  14153. * Convenient class that can be used when creating a `Int8` buffer attribute with
  14154. * a plain `Array` instance.
  14155. *
  14156. * @augments BufferAttribute
  14157. */
  14158. class Int8BufferAttribute extends BufferAttribute {
  14159. /**
  14160. * Constructs a new buffer attribute.
  14161. *
  14162. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  14163. * @param {number} itemSize - The item size.
  14164. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14165. */
  14166. constructor( array, itemSize, normalized ) {
  14167. super( new Int8Array( array ), itemSize, normalized );
  14168. }
  14169. }
  14170. /**
  14171. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  14172. * a plain `Array` instance.
  14173. *
  14174. * @augments BufferAttribute
  14175. */
  14176. class Uint8BufferAttribute extends BufferAttribute {
  14177. /**
  14178. * Constructs a new buffer attribute.
  14179. *
  14180. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  14181. * @param {number} itemSize - The item size.
  14182. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14183. */
  14184. constructor( array, itemSize, normalized ) {
  14185. super( new Uint8Array( array ), itemSize, normalized );
  14186. }
  14187. }
  14188. /**
  14189. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  14190. * a plain `Array` instance.
  14191. *
  14192. * @augments BufferAttribute
  14193. */
  14194. class Uint8ClampedBufferAttribute extends BufferAttribute {
  14195. /**
  14196. * Constructs a new buffer attribute.
  14197. *
  14198. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  14199. * @param {number} itemSize - The item size.
  14200. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14201. */
  14202. constructor( array, itemSize, normalized ) {
  14203. super( new Uint8ClampedArray( array ), itemSize, normalized );
  14204. }
  14205. }
  14206. /**
  14207. * Convenient class that can be used when creating a `Int16` buffer attribute with
  14208. * a plain `Array` instance.
  14209. *
  14210. * @augments BufferAttribute
  14211. */
  14212. class Int16BufferAttribute extends BufferAttribute {
  14213. /**
  14214. * Constructs a new buffer attribute.
  14215. *
  14216. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  14217. * @param {number} itemSize - The item size.
  14218. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14219. */
  14220. constructor( array, itemSize, normalized ) {
  14221. super( new Int16Array( array ), itemSize, normalized );
  14222. }
  14223. }
  14224. /**
  14225. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  14226. * a plain `Array` instance.
  14227. *
  14228. * @augments BufferAttribute
  14229. */
  14230. class Uint16BufferAttribute extends BufferAttribute {
  14231. /**
  14232. * Constructs a new buffer attribute.
  14233. *
  14234. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14235. * @param {number} itemSize - The item size.
  14236. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14237. */
  14238. constructor( array, itemSize, normalized ) {
  14239. super( new Uint16Array( array ), itemSize, normalized );
  14240. }
  14241. }
  14242. /**
  14243. * Convenient class that can be used when creating a `Int32` buffer attribute with
  14244. * a plain `Array` instance.
  14245. *
  14246. * @augments BufferAttribute
  14247. */
  14248. class Int32BufferAttribute extends BufferAttribute {
  14249. /**
  14250. * Constructs a new buffer attribute.
  14251. *
  14252. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  14253. * @param {number} itemSize - The item size.
  14254. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14255. */
  14256. constructor( array, itemSize, normalized ) {
  14257. super( new Int32Array( array ), itemSize, normalized );
  14258. }
  14259. }
  14260. /**
  14261. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  14262. * a plain `Array` instance.
  14263. *
  14264. * @augments BufferAttribute
  14265. */
  14266. class Uint32BufferAttribute extends BufferAttribute {
  14267. /**
  14268. * Constructs a new buffer attribute.
  14269. *
  14270. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14271. * @param {number} itemSize - The item size.
  14272. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14273. */
  14274. constructor( array, itemSize, normalized ) {
  14275. super( new Uint32Array( array ), itemSize, normalized );
  14276. }
  14277. }
  14278. /**
  14279. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14280. * a plain `Array` instance.
  14281. *
  14282. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14283. * browser support is still problematic.
  14284. *
  14285. * @augments BufferAttribute
  14286. */
  14287. class Float16BufferAttribute extends BufferAttribute {
  14288. /**
  14289. * Constructs a new buffer attribute.
  14290. *
  14291. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14292. * @param {number} itemSize - The item size.
  14293. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14294. */
  14295. constructor( array, itemSize, normalized ) {
  14296. super( new Uint16Array( array ), itemSize, normalized );
  14297. this.isFloat16BufferAttribute = true;
  14298. }
  14299. getX( index ) {
  14300. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14301. if ( this.normalized ) x = denormalize( x, this.array );
  14302. return x;
  14303. }
  14304. setX( index, x ) {
  14305. if ( this.normalized ) x = normalize( x, this.array );
  14306. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14307. return this;
  14308. }
  14309. getY( index ) {
  14310. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14311. if ( this.normalized ) y = denormalize( y, this.array );
  14312. return y;
  14313. }
  14314. setY( index, y ) {
  14315. if ( this.normalized ) y = normalize( y, this.array );
  14316. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14317. return this;
  14318. }
  14319. getZ( index ) {
  14320. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14321. if ( this.normalized ) z = denormalize( z, this.array );
  14322. return z;
  14323. }
  14324. setZ( index, z ) {
  14325. if ( this.normalized ) z = normalize( z, this.array );
  14326. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14327. return this;
  14328. }
  14329. getW( index ) {
  14330. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14331. if ( this.normalized ) w = denormalize( w, this.array );
  14332. return w;
  14333. }
  14334. setW( index, w ) {
  14335. if ( this.normalized ) w = normalize( w, this.array );
  14336. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14337. return this;
  14338. }
  14339. setXY( index, x, y ) {
  14340. index *= this.itemSize;
  14341. if ( this.normalized ) {
  14342. x = normalize( x, this.array );
  14343. y = normalize( y, this.array );
  14344. }
  14345. this.array[ index + 0 ] = toHalfFloat( x );
  14346. this.array[ index + 1 ] = toHalfFloat( y );
  14347. return this;
  14348. }
  14349. setXYZ( index, x, y, z ) {
  14350. index *= this.itemSize;
  14351. if ( this.normalized ) {
  14352. x = normalize( x, this.array );
  14353. y = normalize( y, this.array );
  14354. z = normalize( z, this.array );
  14355. }
  14356. this.array[ index + 0 ] = toHalfFloat( x );
  14357. this.array[ index + 1 ] = toHalfFloat( y );
  14358. this.array[ index + 2 ] = toHalfFloat( z );
  14359. return this;
  14360. }
  14361. setXYZW( index, x, y, z, w ) {
  14362. index *= this.itemSize;
  14363. if ( this.normalized ) {
  14364. x = normalize( x, this.array );
  14365. y = normalize( y, this.array );
  14366. z = normalize( z, this.array );
  14367. w = normalize( w, this.array );
  14368. }
  14369. this.array[ index + 0 ] = toHalfFloat( x );
  14370. this.array[ index + 1 ] = toHalfFloat( y );
  14371. this.array[ index + 2 ] = toHalfFloat( z );
  14372. this.array[ index + 3 ] = toHalfFloat( w );
  14373. return this;
  14374. }
  14375. }
  14376. /**
  14377. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14378. * a plain `Array` instance.
  14379. *
  14380. * @augments BufferAttribute
  14381. */
  14382. class Float32BufferAttribute extends BufferAttribute {
  14383. /**
  14384. * Constructs a new buffer attribute.
  14385. *
  14386. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14387. * @param {number} itemSize - The item size.
  14388. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14389. */
  14390. constructor( array, itemSize, normalized ) {
  14391. super( new Float32Array( array ), itemSize, normalized );
  14392. }
  14393. }
  14394. let _id$1 = 0;
  14395. const _m1 = /*@__PURE__*/ new Matrix4();
  14396. const _obj = /*@__PURE__*/ new Object3D();
  14397. const _offset = /*@__PURE__*/ new Vector3();
  14398. const _box$2 = /*@__PURE__*/ new Box3();
  14399. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14400. const _vector$8 = /*@__PURE__*/ new Vector3();
  14401. /**
  14402. * A representation of mesh, line, or point geometry. Includes vertex
  14403. * positions, face indices, normals, colors, UVs, and custom attributes
  14404. * within buffers, reducing the cost of passing all this data to the GPU.
  14405. *
  14406. * ```js
  14407. * const geometry = new THREE.BufferGeometry();
  14408. * // create a simple square shape. We duplicate the top left and bottom right
  14409. * // vertices because each vertex needs to appear once per triangle.
  14410. * const vertices = new Float32Array( [
  14411. * -1.0, -1.0, 1.0, // v0
  14412. * 1.0, -1.0, 1.0, // v1
  14413. * 1.0, 1.0, 1.0, // v2
  14414. *
  14415. * 1.0, 1.0, 1.0, // v3
  14416. * -1.0, 1.0, 1.0, // v4
  14417. * -1.0, -1.0, 1.0 // v5
  14418. * ] );
  14419. * // itemSize = 3 because there are 3 values (components) per vertex
  14420. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14421. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14422. * const mesh = new THREE.Mesh( geometry, material );
  14423. * ```
  14424. *
  14425. * @augments EventDispatcher
  14426. */
  14427. class BufferGeometry extends EventDispatcher {
  14428. /**
  14429. * Constructs a new geometry.
  14430. */
  14431. constructor() {
  14432. super();
  14433. /**
  14434. * This flag can be used for type testing.
  14435. *
  14436. * @type {boolean}
  14437. * @readonly
  14438. * @default true
  14439. */
  14440. this.isBufferGeometry = true;
  14441. /**
  14442. * The ID of the geometry.
  14443. *
  14444. * @name BufferGeometry#id
  14445. * @type {number}
  14446. * @readonly
  14447. */
  14448. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  14449. /**
  14450. * The UUID of the geometry.
  14451. *
  14452. * @type {string}
  14453. * @readonly
  14454. */
  14455. this.uuid = generateUUID();
  14456. /**
  14457. * The name of the geometry.
  14458. *
  14459. * @type {string}
  14460. */
  14461. this.name = '';
  14462. this.type = 'BufferGeometry';
  14463. /**
  14464. * Allows for vertices to be re-used across multiple triangles; this is
  14465. * called using "indexed triangles". Each triangle is associated with the
  14466. * indices of three vertices. This attribute therefore stores the index of
  14467. * each vertex for each triangular face. If this attribute is not set, the
  14468. * renderer assumes that each three contiguous positions represent a single triangle.
  14469. *
  14470. * @type {?BufferAttribute}
  14471. * @default null
  14472. */
  14473. this.index = null;
  14474. /**
  14475. * A (storage) buffer attribute which was generated with a compute shader and
  14476. * now defines indirect draw calls.
  14477. *
  14478. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14479. *
  14480. * @type {?BufferAttribute}
  14481. * @default null
  14482. */
  14483. this.indirect = null;
  14484. /**
  14485. * 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.
  14486. *
  14487. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14488. *
  14489. * @type {number|Array<number>}
  14490. * @default 0
  14491. */
  14492. this.indirectOffset = 0;
  14493. /**
  14494. * This dictionary has as id the name of the attribute to be set and as value
  14495. * the buffer attribute to set it to. Rather than accessing this property directly,
  14496. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14497. *
  14498. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14499. */
  14500. this.attributes = {};
  14501. /**
  14502. * This dictionary holds the morph targets of the geometry.
  14503. *
  14504. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14505. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  14506. *
  14507. * @type {Object}
  14508. */
  14509. this.morphAttributes = {};
  14510. /**
  14511. * Used to control the morph target behavior; when set to `true`, the morph
  14512. * target data is treated as relative offsets, rather than as absolute
  14513. * positions/normals.
  14514. *
  14515. * @type {boolean}
  14516. * @default false
  14517. */
  14518. this.morphTargetsRelative = false;
  14519. /**
  14520. * Split the geometry into groups, each of which will be rendered in a
  14521. * separate draw call. This allows an array of materials to be used with the geometry.
  14522. *
  14523. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14524. *
  14525. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14526. * indices, and must not leave vertices or indices unused.
  14527. *
  14528. * @type {Array<Object>}
  14529. */
  14530. this.groups = [];
  14531. /**
  14532. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14533. *
  14534. * @type {?Box3}
  14535. * @default null
  14536. */
  14537. this.boundingBox = null;
  14538. /**
  14539. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14540. *
  14541. * @type {?Sphere}
  14542. * @default null
  14543. */
  14544. this.boundingSphere = null;
  14545. /**
  14546. * Determines the part of the geometry to render. This should not be set directly,
  14547. * instead use `setDrawRange()`.
  14548. *
  14549. * @type {{start:number,count:number}}
  14550. */
  14551. this.drawRange = { start: 0, count: Infinity };
  14552. /**
  14553. * An object that can be used to store custom data about the geometry.
  14554. * It should not hold references to functions as these will not be cloned.
  14555. *
  14556. * @type {Object}
  14557. */
  14558. this.userData = {};
  14559. }
  14560. /**
  14561. * Returns the index of this geometry.
  14562. *
  14563. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14564. */
  14565. getIndex() {
  14566. return this.index;
  14567. }
  14568. /**
  14569. * Sets the given index to this geometry.
  14570. *
  14571. * @param {Array<number>|BufferAttribute} index - The index to set.
  14572. * @return {BufferGeometry} A reference to this instance.
  14573. */
  14574. setIndex( index ) {
  14575. if ( Array.isArray( index ) ) {
  14576. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14577. } else {
  14578. this.index = index;
  14579. }
  14580. return this;
  14581. }
  14582. /**
  14583. * Sets the given indirect attribute to this geometry.
  14584. *
  14585. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14586. * @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.
  14587. * @return {BufferGeometry} A reference to this instance.
  14588. */
  14589. setIndirect( indirect, indirectOffset = 0 ) {
  14590. this.indirect = indirect;
  14591. this.indirectOffset = indirectOffset;
  14592. return this;
  14593. }
  14594. /**
  14595. * Returns the indirect attribute of this geometry.
  14596. *
  14597. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14598. */
  14599. getIndirect() {
  14600. return this.indirect;
  14601. }
  14602. /**
  14603. * Returns the buffer attribute for the given name.
  14604. *
  14605. * @param {string} name - The attribute name.
  14606. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14607. * Returns `undefined` if not attribute has been found.
  14608. */
  14609. getAttribute( name ) {
  14610. return this.attributes[ name ];
  14611. }
  14612. /**
  14613. * Sets the given attribute for the given name.
  14614. *
  14615. * @param {string} name - The attribute name.
  14616. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14617. * @return {BufferGeometry} A reference to this instance.
  14618. */
  14619. setAttribute( name, attribute ) {
  14620. this.attributes[ name ] = attribute;
  14621. return this;
  14622. }
  14623. /**
  14624. * Deletes the attribute for the given name.
  14625. *
  14626. * @param {string} name - The attribute name to delete.
  14627. * @return {BufferGeometry} A reference to this instance.
  14628. */
  14629. deleteAttribute( name ) {
  14630. delete this.attributes[ name ];
  14631. return this;
  14632. }
  14633. /**
  14634. * Returns `true` if this geometry has an attribute for the given name.
  14635. *
  14636. * @param {string} name - The attribute name.
  14637. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14638. */
  14639. hasAttribute( name ) {
  14640. return this.attributes[ name ] !== undefined;
  14641. }
  14642. /**
  14643. * Adds a group to this geometry.
  14644. *
  14645. * @param {number} start - The first element in this draw call. That is the first
  14646. * vertex for non-indexed geometry, otherwise the first triangle index.
  14647. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14648. * @param {number} [materialIndex=0] - The material array index to use.
  14649. */
  14650. addGroup( start, count, materialIndex = 0 ) {
  14651. this.groups.push( {
  14652. start: start,
  14653. count: count,
  14654. materialIndex: materialIndex
  14655. } );
  14656. }
  14657. /**
  14658. * Clears all groups.
  14659. */
  14660. clearGroups() {
  14661. this.groups = [];
  14662. }
  14663. /**
  14664. * Sets the draw range for this geometry.
  14665. *
  14666. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14667. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14668. * For indexed BufferGeometry, `count` is the number of indices to render.
  14669. */
  14670. setDrawRange( start, count ) {
  14671. this.drawRange.start = start;
  14672. this.drawRange.count = count;
  14673. }
  14674. /**
  14675. * Applies the given 4x4 transformation matrix to the geometry.
  14676. *
  14677. * @param {Matrix4} matrix - The matrix to apply.
  14678. * @return {BufferGeometry} A reference to this instance.
  14679. */
  14680. applyMatrix4( matrix ) {
  14681. const position = this.attributes.position;
  14682. if ( position !== undefined ) {
  14683. position.applyMatrix4( matrix );
  14684. position.needsUpdate = true;
  14685. }
  14686. const normal = this.attributes.normal;
  14687. if ( normal !== undefined ) {
  14688. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14689. normal.applyNormalMatrix( normalMatrix );
  14690. normal.needsUpdate = true;
  14691. }
  14692. const tangent = this.attributes.tangent;
  14693. if ( tangent !== undefined ) {
  14694. tangent.transformDirection( matrix );
  14695. tangent.needsUpdate = true;
  14696. }
  14697. if ( this.boundingBox !== null ) {
  14698. this.computeBoundingBox();
  14699. }
  14700. if ( this.boundingSphere !== null ) {
  14701. this.computeBoundingSphere();
  14702. }
  14703. return this;
  14704. }
  14705. /**
  14706. * Applies the rotation represented by the Quaternion to the geometry.
  14707. *
  14708. * @param {Quaternion} q - The Quaternion to apply.
  14709. * @return {BufferGeometry} A reference to this instance.
  14710. */
  14711. applyQuaternion( q ) {
  14712. _m1.makeRotationFromQuaternion( q );
  14713. this.applyMatrix4( _m1 );
  14714. return this;
  14715. }
  14716. /**
  14717. * Rotates the geometry about the X axis. This is typically done as a one time
  14718. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14719. * real-time mesh rotation.
  14720. *
  14721. * @param {number} angle - The angle in radians.
  14722. * @return {BufferGeometry} A reference to this instance.
  14723. */
  14724. rotateX( angle ) {
  14725. // rotate geometry around world x-axis
  14726. _m1.makeRotationX( angle );
  14727. this.applyMatrix4( _m1 );
  14728. return this;
  14729. }
  14730. /**
  14731. * Rotates the geometry about the Y axis. This is typically done as a one time
  14732. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14733. * real-time mesh rotation.
  14734. *
  14735. * @param {number} angle - The angle in radians.
  14736. * @return {BufferGeometry} A reference to this instance.
  14737. */
  14738. rotateY( angle ) {
  14739. // rotate geometry around world y-axis
  14740. _m1.makeRotationY( angle );
  14741. this.applyMatrix4( _m1 );
  14742. return this;
  14743. }
  14744. /**
  14745. * Rotates the geometry about the Z axis. This is typically done as a one time
  14746. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14747. * real-time mesh rotation.
  14748. *
  14749. * @param {number} angle - The angle in radians.
  14750. * @return {BufferGeometry} A reference to this instance.
  14751. */
  14752. rotateZ( angle ) {
  14753. // rotate geometry around world z-axis
  14754. _m1.makeRotationZ( angle );
  14755. this.applyMatrix4( _m1 );
  14756. return this;
  14757. }
  14758. /**
  14759. * Translates the geometry. This is typically done as a one time
  14760. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14761. * real-time mesh rotation.
  14762. *
  14763. * @param {number} x - The x offset.
  14764. * @param {number} y - The y offset.
  14765. * @param {number} z - The z offset.
  14766. * @return {BufferGeometry} A reference to this instance.
  14767. */
  14768. translate( x, y, z ) {
  14769. // translate geometry
  14770. _m1.makeTranslation( x, y, z );
  14771. this.applyMatrix4( _m1 );
  14772. return this;
  14773. }
  14774. /**
  14775. * Scales the geometry. This is typically done as a one time
  14776. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14777. * real-time mesh rotation.
  14778. *
  14779. * @param {number} x - The x scale.
  14780. * @param {number} y - The y scale.
  14781. * @param {number} z - The z scale.
  14782. * @return {BufferGeometry} A reference to this instance.
  14783. */
  14784. scale( x, y, z ) {
  14785. // scale geometry
  14786. _m1.makeScale( x, y, z );
  14787. this.applyMatrix4( _m1 );
  14788. return this;
  14789. }
  14790. /**
  14791. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14792. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14793. * real-time mesh rotation.
  14794. *
  14795. * @param {Vector3} vector - The target point.
  14796. * @return {BufferGeometry} A reference to this instance.
  14797. */
  14798. lookAt( vector ) {
  14799. _obj.lookAt( vector );
  14800. _obj.updateMatrix();
  14801. this.applyMatrix4( _obj.matrix );
  14802. return this;
  14803. }
  14804. /**
  14805. * Center the geometry based on its bounding box.
  14806. *
  14807. * @return {BufferGeometry} A reference to this instance.
  14808. */
  14809. center() {
  14810. this.computeBoundingBox();
  14811. this.boundingBox.getCenter( _offset ).negate();
  14812. this.translate( _offset.x, _offset.y, _offset.z );
  14813. return this;
  14814. }
  14815. /**
  14816. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14817. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14818. * set to `0`.
  14819. *
  14820. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14821. * data from the array. The length of the array must match the vertex count.
  14822. *
  14823. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14824. * @return {BufferGeometry} A reference to this instance.
  14825. */
  14826. setFromPoints( points ) {
  14827. const positionAttribute = this.getAttribute( 'position' );
  14828. if ( positionAttribute === undefined ) {
  14829. const position = [];
  14830. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14831. const point = points[ i ];
  14832. position.push( point.x, point.y, point.z || 0 );
  14833. }
  14834. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14835. } else {
  14836. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14837. for ( let i = 0; i < l; i ++ ) {
  14838. const point = points[ i ];
  14839. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14840. }
  14841. if ( points.length > positionAttribute.count ) {
  14842. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14843. }
  14844. positionAttribute.needsUpdate = true;
  14845. }
  14846. return this;
  14847. }
  14848. /**
  14849. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14850. * The bounding box is not computed by the engine; it must be computed by your app.
  14851. * You may need to recompute the bounding box if the geometry vertices are modified.
  14852. */
  14853. computeBoundingBox() {
  14854. if ( this.boundingBox === null ) {
  14855. this.boundingBox = new Box3();
  14856. }
  14857. const position = this.attributes.position;
  14858. const morphAttributesPosition = this.morphAttributes.position;
  14859. if ( position && position.isGLBufferAttribute ) {
  14860. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14861. this.boundingBox.set(
  14862. new Vector3( - Infinity, - Infinity, - Infinity ),
  14863. new Vector3( + Infinity, + Infinity, + Infinity )
  14864. );
  14865. return;
  14866. }
  14867. if ( position !== undefined ) {
  14868. this.boundingBox.setFromBufferAttribute( position );
  14869. // process morph attributes if present
  14870. if ( morphAttributesPosition ) {
  14871. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14872. const morphAttribute = morphAttributesPosition[ i ];
  14873. _box$2.setFromBufferAttribute( morphAttribute );
  14874. if ( this.morphTargetsRelative ) {
  14875. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14876. this.boundingBox.expandByPoint( _vector$8 );
  14877. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14878. this.boundingBox.expandByPoint( _vector$8 );
  14879. } else {
  14880. this.boundingBox.expandByPoint( _box$2.min );
  14881. this.boundingBox.expandByPoint( _box$2.max );
  14882. }
  14883. }
  14884. }
  14885. } else {
  14886. this.boundingBox.makeEmpty();
  14887. }
  14888. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14889. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14890. }
  14891. }
  14892. /**
  14893. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14894. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14895. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14896. */
  14897. computeBoundingSphere() {
  14898. if ( this.boundingSphere === null ) {
  14899. this.boundingSphere = new Sphere();
  14900. }
  14901. const position = this.attributes.position;
  14902. const morphAttributesPosition = this.morphAttributes.position;
  14903. if ( position && position.isGLBufferAttribute ) {
  14904. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14905. this.boundingSphere.set( new Vector3(), Infinity );
  14906. return;
  14907. }
  14908. if ( position ) {
  14909. // first, find the center of the bounding sphere
  14910. const center = this.boundingSphere.center;
  14911. _box$2.setFromBufferAttribute( position );
  14912. // process morph attributes if present
  14913. if ( morphAttributesPosition ) {
  14914. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14915. const morphAttribute = morphAttributesPosition[ i ];
  14916. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14917. if ( this.morphTargetsRelative ) {
  14918. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14919. _box$2.expandByPoint( _vector$8 );
  14920. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14921. _box$2.expandByPoint( _vector$8 );
  14922. } else {
  14923. _box$2.expandByPoint( _boxMorphTargets.min );
  14924. _box$2.expandByPoint( _boxMorphTargets.max );
  14925. }
  14926. }
  14927. }
  14928. _box$2.getCenter( center );
  14929. // second, try to find a boundingSphere with a radius smaller than the
  14930. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14931. let maxRadiusSq = 0;
  14932. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14933. _vector$8.fromBufferAttribute( position, i );
  14934. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14935. }
  14936. // process morph attributes if present
  14937. if ( morphAttributesPosition ) {
  14938. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14939. const morphAttribute = morphAttributesPosition[ i ];
  14940. const morphTargetsRelative = this.morphTargetsRelative;
  14941. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14942. _vector$8.fromBufferAttribute( morphAttribute, j );
  14943. if ( morphTargetsRelative ) {
  14944. _offset.fromBufferAttribute( position, j );
  14945. _vector$8.add( _offset );
  14946. }
  14947. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14948. }
  14949. }
  14950. }
  14951. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14952. if ( isNaN( this.boundingSphere.radius ) ) {
  14953. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14954. }
  14955. }
  14956. }
  14957. /**
  14958. * Calculates and adds a tangent attribute to this geometry.
  14959. *
  14960. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14961. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14962. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14963. */
  14964. computeTangents() {
  14965. const index = this.index;
  14966. const attributes = this.attributes;
  14967. // based on http://www.terathon.com/code/tangent.html
  14968. // (per vertex tangents)
  14969. if ( index === null ||
  14970. attributes.position === undefined ||
  14971. attributes.normal === undefined ||
  14972. attributes.uv === undefined ) {
  14973. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14974. return;
  14975. }
  14976. const positionAttribute = attributes.position;
  14977. const normalAttribute = attributes.normal;
  14978. const uvAttribute = attributes.uv;
  14979. if ( this.hasAttribute( 'tangent' ) === false ) {
  14980. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14981. }
  14982. const tangentAttribute = this.getAttribute( 'tangent' );
  14983. const tan1 = [], tan2 = [];
  14984. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14985. tan1[ i ] = new Vector3();
  14986. tan2[ i ] = new Vector3();
  14987. }
  14988. const vA = new Vector3(),
  14989. vB = new Vector3(),
  14990. vC = new Vector3(),
  14991. uvA = new Vector2(),
  14992. uvB = new Vector2(),
  14993. uvC = new Vector2(),
  14994. sdir = new Vector3(),
  14995. tdir = new Vector3();
  14996. function handleTriangle( a, b, c ) {
  14997. vA.fromBufferAttribute( positionAttribute, a );
  14998. vB.fromBufferAttribute( positionAttribute, b );
  14999. vC.fromBufferAttribute( positionAttribute, c );
  15000. uvA.fromBufferAttribute( uvAttribute, a );
  15001. uvB.fromBufferAttribute( uvAttribute, b );
  15002. uvC.fromBufferAttribute( uvAttribute, c );
  15003. vB.sub( vA );
  15004. vC.sub( vA );
  15005. uvB.sub( uvA );
  15006. uvC.sub( uvA );
  15007. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  15008. // silently ignore degenerate uv triangles having coincident or colinear vertices
  15009. if ( ! isFinite( r ) ) return;
  15010. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  15011. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  15012. tan1[ a ].add( sdir );
  15013. tan1[ b ].add( sdir );
  15014. tan1[ c ].add( sdir );
  15015. tan2[ a ].add( tdir );
  15016. tan2[ b ].add( tdir );
  15017. tan2[ c ].add( tdir );
  15018. }
  15019. let groups = this.groups;
  15020. if ( groups.length === 0 ) {
  15021. groups = [ {
  15022. start: 0,
  15023. count: index.count
  15024. } ];
  15025. }
  15026. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  15027. const group = groups[ i ];
  15028. const start = group.start;
  15029. const count = group.count;
  15030. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  15031. handleTriangle(
  15032. index.getX( j + 0 ),
  15033. index.getX( j + 1 ),
  15034. index.getX( j + 2 )
  15035. );
  15036. }
  15037. }
  15038. const tmp = new Vector3(), tmp2 = new Vector3();
  15039. const n = new Vector3(), n2 = new Vector3();
  15040. function handleVertex( v ) {
  15041. n.fromBufferAttribute( normalAttribute, v );
  15042. n2.copy( n );
  15043. const t = tan1[ v ];
  15044. // Gram-Schmidt orthogonalize
  15045. tmp.copy( t );
  15046. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  15047. // Calculate handedness
  15048. tmp2.crossVectors( n2, t );
  15049. const test = tmp2.dot( tan2[ v ] );
  15050. const w = ( test < 0.0 ) ? -1 : 1.0;
  15051. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  15052. }
  15053. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  15054. const group = groups[ i ];
  15055. const start = group.start;
  15056. const count = group.count;
  15057. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  15058. handleVertex( index.getX( j + 0 ) );
  15059. handleVertex( index.getX( j + 1 ) );
  15060. handleVertex( index.getX( j + 2 ) );
  15061. }
  15062. }
  15063. }
  15064. /**
  15065. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  15066. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  15067. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  15068. * to be the same as the face normal.
  15069. */
  15070. computeVertexNormals() {
  15071. const index = this.index;
  15072. const positionAttribute = this.getAttribute( 'position' );
  15073. if ( positionAttribute !== undefined ) {
  15074. let normalAttribute = this.getAttribute( 'normal' );
  15075. if ( normalAttribute === undefined ) {
  15076. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  15077. this.setAttribute( 'normal', normalAttribute );
  15078. } else {
  15079. // reset existing normals to zero
  15080. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  15081. normalAttribute.setXYZ( i, 0, 0, 0 );
  15082. }
  15083. }
  15084. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  15085. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  15086. const cb = new Vector3(), ab = new Vector3();
  15087. // indexed elements
  15088. if ( index ) {
  15089. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  15090. const vA = index.getX( i + 0 );
  15091. const vB = index.getX( i + 1 );
  15092. const vC = index.getX( i + 2 );
  15093. pA.fromBufferAttribute( positionAttribute, vA );
  15094. pB.fromBufferAttribute( positionAttribute, vB );
  15095. pC.fromBufferAttribute( positionAttribute, vC );
  15096. cb.subVectors( pC, pB );
  15097. ab.subVectors( pA, pB );
  15098. cb.cross( ab );
  15099. nA.fromBufferAttribute( normalAttribute, vA );
  15100. nB.fromBufferAttribute( normalAttribute, vB );
  15101. nC.fromBufferAttribute( normalAttribute, vC );
  15102. nA.add( cb );
  15103. nB.add( cb );
  15104. nC.add( cb );
  15105. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  15106. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  15107. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  15108. }
  15109. } else {
  15110. // non-indexed elements (unconnected triangle soup)
  15111. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  15112. pA.fromBufferAttribute( positionAttribute, i + 0 );
  15113. pB.fromBufferAttribute( positionAttribute, i + 1 );
  15114. pC.fromBufferAttribute( positionAttribute, i + 2 );
  15115. cb.subVectors( pC, pB );
  15116. ab.subVectors( pA, pB );
  15117. cb.cross( ab );
  15118. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  15119. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  15120. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  15121. }
  15122. }
  15123. this.normalizeNormals();
  15124. normalAttribute.needsUpdate = true;
  15125. }
  15126. }
  15127. /**
  15128. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  15129. * correct lighting on the geometry surfaces.
  15130. */
  15131. normalizeNormals() {
  15132. const normals = this.attributes.normal;
  15133. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  15134. _vector$8.fromBufferAttribute( normals, i );
  15135. _vector$8.normalize();
  15136. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  15137. }
  15138. }
  15139. /**
  15140. * Return a new non-index version of this indexed geometry. If the geometry
  15141. * is already non-indexed, the method is a NOOP.
  15142. *
  15143. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  15144. */
  15145. toNonIndexed() {
  15146. function convertBufferAttribute( attribute, indices ) {
  15147. const array = attribute.array;
  15148. const itemSize = attribute.itemSize;
  15149. const normalized = attribute.normalized;
  15150. const array2 = new array.constructor( indices.length * itemSize );
  15151. let index = 0, index2 = 0;
  15152. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  15153. if ( attribute.isInterleavedBufferAttribute ) {
  15154. index = indices[ i ] * attribute.data.stride + attribute.offset;
  15155. } else {
  15156. index = indices[ i ] * itemSize;
  15157. }
  15158. for ( let j = 0; j < itemSize; j ++ ) {
  15159. array2[ index2 ++ ] = array[ index ++ ];
  15160. }
  15161. }
  15162. return new BufferAttribute( array2, itemSize, normalized );
  15163. }
  15164. //
  15165. if ( this.index === null ) {
  15166. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  15167. return this;
  15168. }
  15169. const geometry2 = new BufferGeometry();
  15170. const indices = this.index.array;
  15171. const attributes = this.attributes;
  15172. // attributes
  15173. for ( const name in attributes ) {
  15174. const attribute = attributes[ name ];
  15175. const newAttribute = convertBufferAttribute( attribute, indices );
  15176. geometry2.setAttribute( name, newAttribute );
  15177. }
  15178. // morph attributes
  15179. const morphAttributes = this.morphAttributes;
  15180. for ( const name in morphAttributes ) {
  15181. const morphArray = [];
  15182. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15183. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  15184. const attribute = morphAttribute[ i ];
  15185. const newAttribute = convertBufferAttribute( attribute, indices );
  15186. morphArray.push( newAttribute );
  15187. }
  15188. geometry2.morphAttributes[ name ] = morphArray;
  15189. }
  15190. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  15191. // groups
  15192. const groups = this.groups;
  15193. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15194. const group = groups[ i ];
  15195. geometry2.addGroup( group.start, group.count, group.materialIndex );
  15196. }
  15197. return geometry2;
  15198. }
  15199. /**
  15200. * Serializes the geometry into JSON.
  15201. *
  15202. * @return {Object} A JSON object representing the serialized geometry.
  15203. */
  15204. toJSON() {
  15205. const data = {
  15206. metadata: {
  15207. version: 4.7,
  15208. type: 'BufferGeometry',
  15209. generator: 'BufferGeometry.toJSON'
  15210. }
  15211. };
  15212. // standard BufferGeometry serialization
  15213. data.uuid = this.uuid;
  15214. data.type = this.type;
  15215. if ( this.name !== '' ) data.name = this.name;
  15216. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15217. if ( this.parameters !== undefined ) {
  15218. const parameters = this.parameters;
  15219. for ( const key in parameters ) {
  15220. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  15221. }
  15222. return data;
  15223. }
  15224. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  15225. data.data = { attributes: {} };
  15226. const index = this.index;
  15227. if ( index !== null ) {
  15228. data.data.index = {
  15229. type: index.array.constructor.name,
  15230. array: Array.prototype.slice.call( index.array )
  15231. };
  15232. }
  15233. const attributes = this.attributes;
  15234. for ( const key in attributes ) {
  15235. const attribute = attributes[ key ];
  15236. data.data.attributes[ key ] = attribute.toJSON( data.data );
  15237. }
  15238. const morphAttributes = {};
  15239. let hasMorphAttributes = false;
  15240. for ( const key in this.morphAttributes ) {
  15241. const attributeArray = this.morphAttributes[ key ];
  15242. const array = [];
  15243. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  15244. const attribute = attributeArray[ i ];
  15245. array.push( attribute.toJSON( data.data ) );
  15246. }
  15247. if ( array.length > 0 ) {
  15248. morphAttributes[ key ] = array;
  15249. hasMorphAttributes = true;
  15250. }
  15251. }
  15252. if ( hasMorphAttributes ) {
  15253. data.data.morphAttributes = morphAttributes;
  15254. data.data.morphTargetsRelative = this.morphTargetsRelative;
  15255. }
  15256. const groups = this.groups;
  15257. if ( groups.length > 0 ) {
  15258. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  15259. }
  15260. const boundingSphere = this.boundingSphere;
  15261. if ( boundingSphere !== null ) {
  15262. data.data.boundingSphere = boundingSphere.toJSON();
  15263. }
  15264. return data;
  15265. }
  15266. /**
  15267. * Returns a new geometry with copied values from this instance.
  15268. *
  15269. * @return {BufferGeometry} A clone of this instance.
  15270. */
  15271. clone() {
  15272. return new this.constructor().copy( this );
  15273. }
  15274. /**
  15275. * Copies the values of the given geometry to this instance.
  15276. *
  15277. * @param {BufferGeometry} source - The geometry to copy.
  15278. * @return {BufferGeometry} A reference to this instance.
  15279. */
  15280. copy( source ) {
  15281. // reset
  15282. this.index = null;
  15283. this.attributes = {};
  15284. this.morphAttributes = {};
  15285. this.groups = [];
  15286. this.boundingBox = null;
  15287. this.boundingSphere = null;
  15288. // used for storing cloned, shared data
  15289. const data = {};
  15290. // name
  15291. this.name = source.name;
  15292. // index
  15293. const index = source.index;
  15294. if ( index !== null ) {
  15295. this.setIndex( index.clone() );
  15296. }
  15297. // attributes
  15298. const attributes = source.attributes;
  15299. for ( const name in attributes ) {
  15300. const attribute = attributes[ name ];
  15301. this.setAttribute( name, attribute.clone( data ) );
  15302. }
  15303. // morph attributes
  15304. const morphAttributes = source.morphAttributes;
  15305. for ( const name in morphAttributes ) {
  15306. const array = [];
  15307. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15308. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15309. array.push( morphAttribute[ i ].clone( data ) );
  15310. }
  15311. this.morphAttributes[ name ] = array;
  15312. }
  15313. this.morphTargetsRelative = source.morphTargetsRelative;
  15314. // groups
  15315. const groups = source.groups;
  15316. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15317. const group = groups[ i ];
  15318. this.addGroup( group.start, group.count, group.materialIndex );
  15319. }
  15320. // bounding box
  15321. const boundingBox = source.boundingBox;
  15322. if ( boundingBox !== null ) {
  15323. this.boundingBox = boundingBox.clone();
  15324. }
  15325. // bounding sphere
  15326. const boundingSphere = source.boundingSphere;
  15327. if ( boundingSphere !== null ) {
  15328. this.boundingSphere = boundingSphere.clone();
  15329. }
  15330. // draw range
  15331. this.drawRange.start = source.drawRange.start;
  15332. this.drawRange.count = source.drawRange.count;
  15333. // user data
  15334. this.userData = source.userData;
  15335. return this;
  15336. }
  15337. /**
  15338. * Frees the GPU-related resources allocated by this instance. Call this
  15339. * method whenever this instance is no longer used in your app.
  15340. *
  15341. * @fires BufferGeometry#dispose
  15342. */
  15343. dispose() {
  15344. this.dispatchEvent( { type: 'dispose' } );
  15345. }
  15346. }
  15347. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15348. const _ray$3 = /*@__PURE__*/ new Ray();
  15349. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15350. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15351. const _vA$1 = /*@__PURE__*/ new Vector3();
  15352. const _vB$1 = /*@__PURE__*/ new Vector3();
  15353. const _vC$1 = /*@__PURE__*/ new Vector3();
  15354. const _tempA = /*@__PURE__*/ new Vector3();
  15355. const _morphA = /*@__PURE__*/ new Vector3();
  15356. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15357. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15358. /**
  15359. * Class representing triangular polygon mesh based objects.
  15360. *
  15361. * ```js
  15362. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15363. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15364. * const mesh = new THREE.Mesh( geometry, material );
  15365. * scene.add( mesh );
  15366. * ```
  15367. *
  15368. * @augments Object3D
  15369. */
  15370. class Mesh extends Object3D {
  15371. /**
  15372. * Constructs a new mesh.
  15373. *
  15374. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15375. * @param {Material|Array<Material>} [material] - The mesh material.
  15376. */
  15377. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15378. super();
  15379. /**
  15380. * This flag can be used for type testing.
  15381. *
  15382. * @type {boolean}
  15383. * @readonly
  15384. * @default true
  15385. */
  15386. this.isMesh = true;
  15387. this.type = 'Mesh';
  15388. /**
  15389. * The mesh geometry.
  15390. *
  15391. * @type {BufferGeometry}
  15392. */
  15393. this.geometry = geometry;
  15394. /**
  15395. * The mesh material.
  15396. *
  15397. * @type {Material|Array<Material>}
  15398. * @default MeshBasicMaterial
  15399. */
  15400. this.material = material;
  15401. /**
  15402. * A dictionary representing the morph targets in the geometry. The key is the
  15403. * morph targets name, the value its attribute index. This member is `undefined`
  15404. * by default and only set when morph targets are detected in the geometry.
  15405. *
  15406. * @type {Object<string,number>|undefined}
  15407. * @default undefined
  15408. */
  15409. this.morphTargetDictionary = undefined;
  15410. /**
  15411. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15412. * is applied. This member is `undefined` by default and only set when morph targets are
  15413. * detected in the geometry.
  15414. *
  15415. * @type {Array<number>|undefined}
  15416. * @default undefined
  15417. */
  15418. this.morphTargetInfluences = undefined;
  15419. /**
  15420. * The number of instances of this mesh.
  15421. * Can only be used with {@link WebGPURenderer}.
  15422. *
  15423. * @type {number}
  15424. * @default 1
  15425. */
  15426. this.count = 1;
  15427. this.updateMorphTargets();
  15428. }
  15429. copy( source, recursive ) {
  15430. super.copy( source, recursive );
  15431. if ( source.morphTargetInfluences !== undefined ) {
  15432. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15433. }
  15434. if ( source.morphTargetDictionary !== undefined ) {
  15435. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15436. }
  15437. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15438. this.geometry = source.geometry;
  15439. return this;
  15440. }
  15441. /**
  15442. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15443. * to make sure existing morph targets can influence this 3D object.
  15444. */
  15445. updateMorphTargets() {
  15446. const geometry = this.geometry;
  15447. const morphAttributes = geometry.morphAttributes;
  15448. const keys = Object.keys( morphAttributes );
  15449. if ( keys.length > 0 ) {
  15450. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15451. if ( morphAttribute !== undefined ) {
  15452. this.morphTargetInfluences = [];
  15453. this.morphTargetDictionary = {};
  15454. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15455. const name = morphAttribute[ m ].name || String( m );
  15456. this.morphTargetInfluences.push( 0 );
  15457. this.morphTargetDictionary[ name ] = m;
  15458. }
  15459. }
  15460. }
  15461. }
  15462. /**
  15463. * Returns the local-space position of the vertex at the given index, taking into
  15464. * account the current animation state of both morph targets and skinning.
  15465. *
  15466. * @param {number} index - The vertex index.
  15467. * @param {Vector3} target - The target object that is used to store the method's result.
  15468. * @return {Vector3} The vertex position in local space.
  15469. */
  15470. getVertexPosition( index, target ) {
  15471. const geometry = this.geometry;
  15472. const position = geometry.attributes.position;
  15473. const morphPosition = geometry.morphAttributes.position;
  15474. const morphTargetsRelative = geometry.morphTargetsRelative;
  15475. target.fromBufferAttribute( position, index );
  15476. const morphInfluences = this.morphTargetInfluences;
  15477. if ( morphPosition && morphInfluences ) {
  15478. _morphA.set( 0, 0, 0 );
  15479. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15480. const influence = morphInfluences[ i ];
  15481. const morphAttribute = morphPosition[ i ];
  15482. if ( influence === 0 ) continue;
  15483. _tempA.fromBufferAttribute( morphAttribute, index );
  15484. if ( morphTargetsRelative ) {
  15485. _morphA.addScaledVector( _tempA, influence );
  15486. } else {
  15487. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15488. }
  15489. }
  15490. target.add( _morphA );
  15491. }
  15492. return target;
  15493. }
  15494. /**
  15495. * Computes intersection points between a casted ray and this line.
  15496. *
  15497. * @param {Raycaster} raycaster - The raycaster.
  15498. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15499. */
  15500. raycast( raycaster, intersects ) {
  15501. const geometry = this.geometry;
  15502. const material = this.material;
  15503. const matrixWorld = this.matrixWorld;
  15504. if ( material === undefined ) return;
  15505. // test with bounding sphere in world space
  15506. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15507. _sphere$6.copy( geometry.boundingSphere );
  15508. _sphere$6.applyMatrix4( matrixWorld );
  15509. // check distance from ray origin to bounding sphere
  15510. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15511. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15512. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15513. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15514. }
  15515. // convert ray to local space of mesh
  15516. _inverseMatrix$3.copy( matrixWorld ).invert();
  15517. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15518. // test with bounding box in local space
  15519. if ( geometry.boundingBox !== null ) {
  15520. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15521. }
  15522. // test for intersections with geometry
  15523. this._computeIntersections( raycaster, intersects, _ray$3 );
  15524. }
  15525. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15526. let intersection;
  15527. const geometry = this.geometry;
  15528. const material = this.material;
  15529. const index = geometry.index;
  15530. const position = geometry.attributes.position;
  15531. const uv = geometry.attributes.uv;
  15532. const uv1 = geometry.attributes.uv1;
  15533. const normal = geometry.attributes.normal;
  15534. const groups = geometry.groups;
  15535. const drawRange = geometry.drawRange;
  15536. if ( index !== null ) {
  15537. // indexed buffer geometry
  15538. if ( Array.isArray( material ) ) {
  15539. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15540. const group = groups[ i ];
  15541. const groupMaterial = material[ group.materialIndex ];
  15542. const start = Math.max( group.start, drawRange.start );
  15543. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15544. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15545. const a = index.getX( j );
  15546. const b = index.getX( j + 1 );
  15547. const c = index.getX( j + 2 );
  15548. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15549. if ( intersection ) {
  15550. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15551. intersection.face.materialIndex = group.materialIndex;
  15552. intersects.push( intersection );
  15553. }
  15554. }
  15555. }
  15556. } else {
  15557. const start = Math.max( 0, drawRange.start );
  15558. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15559. for ( let i = start, il = end; i < il; i += 3 ) {
  15560. const a = index.getX( i );
  15561. const b = index.getX( i + 1 );
  15562. const c = index.getX( i + 2 );
  15563. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15564. if ( intersection ) {
  15565. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15566. intersects.push( intersection );
  15567. }
  15568. }
  15569. }
  15570. } else if ( position !== undefined ) {
  15571. // non-indexed buffer geometry
  15572. if ( Array.isArray( material ) ) {
  15573. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15574. const group = groups[ i ];
  15575. const groupMaterial = material[ group.materialIndex ];
  15576. const start = Math.max( group.start, drawRange.start );
  15577. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15578. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15579. const a = j;
  15580. const b = j + 1;
  15581. const c = j + 2;
  15582. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15583. if ( intersection ) {
  15584. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15585. intersection.face.materialIndex = group.materialIndex;
  15586. intersects.push( intersection );
  15587. }
  15588. }
  15589. }
  15590. } else {
  15591. const start = Math.max( 0, drawRange.start );
  15592. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15593. for ( let i = start, il = end; i < il; i += 3 ) {
  15594. const a = i;
  15595. const b = i + 1;
  15596. const c = i + 2;
  15597. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15598. if ( intersection ) {
  15599. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15600. intersects.push( intersection );
  15601. }
  15602. }
  15603. }
  15604. }
  15605. }
  15606. }
  15607. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15608. let intersect;
  15609. if ( material.side === BackSide ) {
  15610. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15611. } else {
  15612. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15613. }
  15614. if ( intersect === null ) return null;
  15615. _intersectionPointWorld.copy( point );
  15616. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15617. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15618. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15619. return {
  15620. distance: distance,
  15621. point: _intersectionPointWorld.clone(),
  15622. object: object
  15623. };
  15624. }
  15625. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15626. object.getVertexPosition( a, _vA$1 );
  15627. object.getVertexPosition( b, _vB$1 );
  15628. object.getVertexPosition( c, _vC$1 );
  15629. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15630. if ( intersection ) {
  15631. const barycoord = new Vector3();
  15632. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15633. if ( uv ) {
  15634. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15635. }
  15636. if ( uv1 ) {
  15637. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15638. }
  15639. if ( normal ) {
  15640. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15641. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15642. intersection.normal.multiplyScalar( -1 );
  15643. }
  15644. }
  15645. const face = {
  15646. a: a,
  15647. b: b,
  15648. c: c,
  15649. normal: new Vector3(),
  15650. materialIndex: 0
  15651. };
  15652. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15653. intersection.face = face;
  15654. intersection.barycoord = barycoord;
  15655. }
  15656. return intersection;
  15657. }
  15658. /**
  15659. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15660. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15661. * of the axes.
  15662. *
  15663. * ```js
  15664. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15665. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15666. * const cube = new THREE.Mesh( geometry, material );
  15667. * scene.add( cube );
  15668. * ```
  15669. *
  15670. * @augments BufferGeometry
  15671. * @demo scenes/geometry-browser.html#BoxGeometry
  15672. */
  15673. class BoxGeometry extends BufferGeometry {
  15674. /**
  15675. * Constructs a new box geometry.
  15676. *
  15677. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15678. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15679. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15680. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15681. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15682. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15683. */
  15684. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15685. super();
  15686. this.type = 'BoxGeometry';
  15687. /**
  15688. * Holds the constructor parameters that have been
  15689. * used to generate the geometry. Any modification
  15690. * after instantiation does not change the geometry.
  15691. *
  15692. * @type {Object}
  15693. */
  15694. this.parameters = {
  15695. width: width,
  15696. height: height,
  15697. depth: depth,
  15698. widthSegments: widthSegments,
  15699. heightSegments: heightSegments,
  15700. depthSegments: depthSegments
  15701. };
  15702. const scope = this;
  15703. // segments
  15704. widthSegments = Math.floor( widthSegments );
  15705. heightSegments = Math.floor( heightSegments );
  15706. depthSegments = Math.floor( depthSegments );
  15707. // buffers
  15708. const indices = [];
  15709. const vertices = [];
  15710. const normals = [];
  15711. const uvs = [];
  15712. // helper variables
  15713. let numberOfVertices = 0;
  15714. let groupStart = 0;
  15715. // build each side of the box geometry
  15716. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15717. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15718. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15719. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15720. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15721. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15722. // build geometry
  15723. this.setIndex( indices );
  15724. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15725. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15726. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15727. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15728. const segmentWidth = width / gridX;
  15729. const segmentHeight = height / gridY;
  15730. const widthHalf = width / 2;
  15731. const heightHalf = height / 2;
  15732. const depthHalf = depth / 2;
  15733. const gridX1 = gridX + 1;
  15734. const gridY1 = gridY + 1;
  15735. let vertexCounter = 0;
  15736. let groupCount = 0;
  15737. const vector = new Vector3();
  15738. // generate vertices, normals and uvs
  15739. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15740. const y = iy * segmentHeight - heightHalf;
  15741. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15742. const x = ix * segmentWidth - widthHalf;
  15743. // set values to correct vector component
  15744. vector[ u ] = x * udir;
  15745. vector[ v ] = y * vdir;
  15746. vector[ w ] = depthHalf;
  15747. // now apply vector to vertex buffer
  15748. vertices.push( vector.x, vector.y, vector.z );
  15749. // set values to correct vector component
  15750. vector[ u ] = 0;
  15751. vector[ v ] = 0;
  15752. vector[ w ] = depth > 0 ? 1 : -1;
  15753. // now apply vector to normal buffer
  15754. normals.push( vector.x, vector.y, vector.z );
  15755. // uvs
  15756. uvs.push( ix / gridX );
  15757. uvs.push( 1 - ( iy / gridY ) );
  15758. // counters
  15759. vertexCounter += 1;
  15760. }
  15761. }
  15762. // indices
  15763. // 1. you need three indices to draw a single face
  15764. // 2. a single segment consists of two faces
  15765. // 3. so we need to generate six (2*3) indices per segment
  15766. for ( let iy = 0; iy < gridY; iy ++ ) {
  15767. for ( let ix = 0; ix < gridX; ix ++ ) {
  15768. const a = numberOfVertices + ix + gridX1 * iy;
  15769. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15770. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15771. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15772. // faces
  15773. indices.push( a, b, d );
  15774. indices.push( b, c, d );
  15775. // increase counter
  15776. groupCount += 6;
  15777. }
  15778. }
  15779. // add a group to the geometry. this will ensure multi material support
  15780. scope.addGroup( groupStart, groupCount, materialIndex );
  15781. // calculate new start value for groups
  15782. groupStart += groupCount;
  15783. // update total number of vertices
  15784. numberOfVertices += vertexCounter;
  15785. }
  15786. }
  15787. copy( source ) {
  15788. super.copy( source );
  15789. this.parameters = Object.assign( {}, source.parameters );
  15790. return this;
  15791. }
  15792. /**
  15793. * Factory method for creating an instance of this class from the given
  15794. * JSON object.
  15795. *
  15796. * @param {Object} data - A JSON object representing the serialized geometry.
  15797. * @return {BoxGeometry} A new instance.
  15798. */
  15799. static fromJSON( data ) {
  15800. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15801. }
  15802. }
  15803. /**
  15804. * Provides utility functions for managing uniforms.
  15805. *
  15806. * @module UniformsUtils
  15807. */
  15808. /**
  15809. * Clones the given uniform definitions by performing a deep-copy. That means
  15810. * if the value of a uniform refers to an object like a Vector3 or Texture,
  15811. * the cloned uniform will refer to a new object reference.
  15812. *
  15813. * @param {Object} src - An object representing uniform definitions.
  15814. * @return {Object} The cloned uniforms.
  15815. */
  15816. function cloneUniforms( src ) {
  15817. const dst = {};
  15818. for ( const u in src ) {
  15819. dst[ u ] = {};
  15820. for ( const p in src[ u ] ) {
  15821. const property = src[ u ][ p ];
  15822. if ( property && ( property.isColor ||
  15823. property.isMatrix3 || property.isMatrix4 ||
  15824. property.isVector2 || property.isVector3 || property.isVector4 ||
  15825. property.isTexture || property.isQuaternion ) ) {
  15826. if ( property.isRenderTargetTexture ) {
  15827. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15828. dst[ u ][ p ] = null;
  15829. } else {
  15830. dst[ u ][ p ] = property.clone();
  15831. }
  15832. } else if ( Array.isArray( property ) ) {
  15833. dst[ u ][ p ] = property.slice();
  15834. } else {
  15835. dst[ u ][ p ] = property;
  15836. }
  15837. }
  15838. }
  15839. return dst;
  15840. }
  15841. /**
  15842. * Merges the given uniform definitions into a single object. Since the
  15843. * method internally uses cloneUniforms(), it performs a deep-copy when
  15844. * producing the merged uniform definitions.
  15845. *
  15846. * @param {Array} uniforms - An array of objects containing uniform definitions.
  15847. * @return {Object} The merged uniforms.
  15848. */
  15849. function mergeUniforms( uniforms ) {
  15850. const merged = {};
  15851. for ( let u = 0; u < uniforms.length; u ++ ) {
  15852. const tmp = cloneUniforms( uniforms[ u ] );
  15853. for ( const p in tmp ) {
  15854. merged[ p ] = tmp[ p ];
  15855. }
  15856. }
  15857. return merged;
  15858. }
  15859. function cloneUniformsGroups( src ) {
  15860. const dst = [];
  15861. for ( let u = 0; u < src.length; u ++ ) {
  15862. dst.push( src[ u ].clone() );
  15863. }
  15864. return dst;
  15865. }
  15866. function getUnlitUniformColorSpace( renderer ) {
  15867. const currentRenderTarget = renderer.getRenderTarget();
  15868. if ( currentRenderTarget === null ) {
  15869. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15870. return renderer.outputColorSpace;
  15871. }
  15872. // https://github.com/mrdoob/three.js/issues/27868
  15873. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15874. return currentRenderTarget.texture.colorSpace;
  15875. }
  15876. return ColorManagement.workingColorSpace;
  15877. }
  15878. // Legacy
  15879. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15880. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15881. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15882. /**
  15883. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15884. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15885. * effect not included with any of the built-in materials.
  15886. *
  15887. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15888. *
  15889. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15890. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15891. * you don't want that, use {@link RawShaderMaterial} instead.
  15892. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15893. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15894. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15895. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  15896. * - The loop variable has to be *i*.
  15897. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15898. * value of *i* for the given iteration and can be used in preprocessor
  15899. * statements.
  15900. *
  15901. * ```js
  15902. * const material = new THREE.ShaderMaterial( {
  15903. * uniforms: {
  15904. * time: { value: 1.0 },
  15905. * resolution: { value: new THREE.Vector2() }
  15906. * },
  15907. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15908. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15909. * } );
  15910. * ```
  15911. *
  15912. * @augments Material
  15913. */
  15914. class ShaderMaterial extends Material {
  15915. /**
  15916. * Constructs a new shader material.
  15917. *
  15918. * @param {Object} [parameters] - An object with one or more properties
  15919. * defining the material's appearance. Any property of the material
  15920. * (including any property from inherited materials) can be passed
  15921. * in here. Color values can be passed any type of value accepted
  15922. * by {@link Color#set}.
  15923. */
  15924. constructor( parameters ) {
  15925. super();
  15926. /**
  15927. * This flag can be used for type testing.
  15928. *
  15929. * @type {boolean}
  15930. * @readonly
  15931. * @default true
  15932. */
  15933. this.isShaderMaterial = true;
  15934. this.type = 'ShaderMaterial';
  15935. /**
  15936. * Defines custom constants using `#define` directives within the GLSL code
  15937. * for both the vertex shader and the fragment shader; each key/value pair
  15938. * yields another directive.
  15939. * ```js
  15940. * defines: {
  15941. * FOO: 15,
  15942. * BAR: true
  15943. * }
  15944. * ```
  15945. * Yields the lines:
  15946. * ```
  15947. * #define FOO 15
  15948. * #define BAR true
  15949. * ```
  15950. *
  15951. * @type {Object}
  15952. */
  15953. this.defines = {};
  15954. /**
  15955. * An object of the form:
  15956. * ```js
  15957. * {
  15958. * "uniform1": { value: 1.0 },
  15959. * "uniform2": { value: 2 }
  15960. * }
  15961. * ```
  15962. * specifying the uniforms to be passed to the shader code; keys are uniform
  15963. * names, values are definitions of the form
  15964. * ```
  15965. * {
  15966. * value: 1.0
  15967. * }
  15968. * ```
  15969. * where `value` is the value of the uniform. Names must match the name of
  15970. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15971. * on every frame, so updating the value of the uniform will immediately
  15972. * update the value available to the GLSL code.
  15973. *
  15974. * @type {Object}
  15975. */
  15976. this.uniforms = {};
  15977. /**
  15978. * An array holding uniforms groups for configuring UBOs.
  15979. *
  15980. * @type {Array<UniformsGroup>}
  15981. */
  15982. this.uniformsGroups = [];
  15983. /**
  15984. * Vertex shader GLSL code. This is the actual code for the shader.
  15985. *
  15986. * @type {string}
  15987. */
  15988. this.vertexShader = default_vertex;
  15989. /**
  15990. * Fragment shader GLSL code. This is the actual code for the shader.
  15991. *
  15992. * @type {string}
  15993. */
  15994. this.fragmentShader = default_fragment;
  15995. /**
  15996. * Controls line thickness or lines.
  15997. *
  15998. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15999. * width of one pixel.
  16000. *
  16001. * @type {number}
  16002. * @default 1
  16003. */
  16004. this.linewidth = 1;
  16005. /**
  16006. * Renders the geometry as a wireframe.
  16007. *
  16008. * @type {boolean}
  16009. * @default false
  16010. */
  16011. this.wireframe = false;
  16012. /**
  16013. * Controls the thickness of the wireframe.
  16014. *
  16015. * WebGL and WebGPU ignore this property and always render
  16016. * 1 pixel wide lines.
  16017. *
  16018. * @type {number}
  16019. * @default 1
  16020. */
  16021. this.wireframeLinewidth = 1;
  16022. /**
  16023. * Defines whether the material color is affected by global fog settings; `true`
  16024. * to pass fog uniforms to the shader.
  16025. *
  16026. * Setting this property to `true` requires the definition of fog uniforms. It is
  16027. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  16028. * with predefined fog uniforms.
  16029. *
  16030. * ```js
  16031. * const material = new ShaderMaterial( {
  16032. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  16033. * vertexShader: vertexShader,
  16034. * fragmentShader: fragmentShader,
  16035. * fog: true
  16036. * } );
  16037. * ```
  16038. *
  16039. * @type {boolean}
  16040. * @default false
  16041. */
  16042. this.fog = false;
  16043. /**
  16044. * Defines whether this material uses lighting; `true` to pass uniform data
  16045. * related to lighting to this shader.
  16046. *
  16047. * @type {boolean}
  16048. * @default false
  16049. */
  16050. this.lights = false;
  16051. /**
  16052. * Defines whether this material supports clipping; `true` to let the renderer
  16053. * pass the clippingPlanes uniform.
  16054. *
  16055. * @type {boolean}
  16056. * @default false
  16057. */
  16058. this.clipping = false;
  16059. /**
  16060. * Overwritten and set to `true` by default.
  16061. *
  16062. * @type {boolean}
  16063. * @default true
  16064. */
  16065. this.forceSinglePass = true;
  16066. /**
  16067. * This object allows to enable certain WebGL 2 extensions.
  16068. *
  16069. * - clipCullDistance: set to `true` to use vertex shader clipping
  16070. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  16071. *
  16072. * @type {{clipCullDistance:false,multiDraw:false}}
  16073. */
  16074. this.extensions = {
  16075. clipCullDistance: false, // set to use vertex shader clipping
  16076. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  16077. };
  16078. /**
  16079. * When the rendered geometry doesn't include these attributes but the
  16080. * material does, these default values will be passed to the shaders. This
  16081. * avoids errors when buffer data is missing.
  16082. *
  16083. * - color: [ 1, 1, 1 ]
  16084. * - uv: [ 0, 0 ]
  16085. * - uv1: [ 0, 0 ]
  16086. *
  16087. * @type {Object}
  16088. */
  16089. this.defaultAttributeValues = {
  16090. 'color': [ 1, 1, 1 ],
  16091. 'uv': [ 0, 0 ],
  16092. 'uv1': [ 0, 0 ]
  16093. };
  16094. /**
  16095. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  16096. * to bind a generic vertex index to an attribute variable.
  16097. *
  16098. * @type {string|undefined}
  16099. * @default undefined
  16100. */
  16101. this.index0AttributeName = undefined;
  16102. /**
  16103. * Can be used to force a uniform update while changing uniforms in
  16104. * {@link Object3D#onBeforeRender}.
  16105. *
  16106. * @type {boolean}
  16107. * @default false
  16108. */
  16109. this.uniformsNeedUpdate = false;
  16110. /**
  16111. * Defines the GLSL version of custom shader code.
  16112. *
  16113. * @type {?(GLSL1|GLSL3)}
  16114. * @default null
  16115. */
  16116. this.glslVersion = null;
  16117. if ( parameters !== undefined ) {
  16118. this.setValues( parameters );
  16119. }
  16120. }
  16121. copy( source ) {
  16122. super.copy( source );
  16123. this.fragmentShader = source.fragmentShader;
  16124. this.vertexShader = source.vertexShader;
  16125. this.uniforms = cloneUniforms( source.uniforms );
  16126. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  16127. this.defines = Object.assign( {}, source.defines );
  16128. this.wireframe = source.wireframe;
  16129. this.wireframeLinewidth = source.wireframeLinewidth;
  16130. this.fog = source.fog;
  16131. this.lights = source.lights;
  16132. this.clipping = source.clipping;
  16133. this.extensions = Object.assign( {}, source.extensions );
  16134. this.glslVersion = source.glslVersion;
  16135. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  16136. this.index0AttributeName = source.index0AttributeName;
  16137. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  16138. return this;
  16139. }
  16140. toJSON( meta ) {
  16141. const data = super.toJSON( meta );
  16142. data.glslVersion = this.glslVersion;
  16143. data.uniforms = {};
  16144. for ( const name in this.uniforms ) {
  16145. const uniform = this.uniforms[ name ];
  16146. const value = uniform.value;
  16147. if ( value && value.isTexture ) {
  16148. data.uniforms[ name ] = {
  16149. type: 't',
  16150. value: value.toJSON( meta ).uuid
  16151. };
  16152. } else if ( value && value.isColor ) {
  16153. data.uniforms[ name ] = {
  16154. type: 'c',
  16155. value: value.getHex()
  16156. };
  16157. } else if ( value && value.isVector2 ) {
  16158. data.uniforms[ name ] = {
  16159. type: 'v2',
  16160. value: value.toArray()
  16161. };
  16162. } else if ( value && value.isVector3 ) {
  16163. data.uniforms[ name ] = {
  16164. type: 'v3',
  16165. value: value.toArray()
  16166. };
  16167. } else if ( value && value.isVector4 ) {
  16168. data.uniforms[ name ] = {
  16169. type: 'v4',
  16170. value: value.toArray()
  16171. };
  16172. } else if ( value && value.isMatrix3 ) {
  16173. data.uniforms[ name ] = {
  16174. type: 'm3',
  16175. value: value.toArray()
  16176. };
  16177. } else if ( value && value.isMatrix4 ) {
  16178. data.uniforms[ name ] = {
  16179. type: 'm4',
  16180. value: value.toArray()
  16181. };
  16182. } else {
  16183. data.uniforms[ name ] = {
  16184. value: value
  16185. };
  16186. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  16187. }
  16188. }
  16189. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  16190. data.vertexShader = this.vertexShader;
  16191. data.fragmentShader = this.fragmentShader;
  16192. data.lights = this.lights;
  16193. data.clipping = this.clipping;
  16194. const extensions = {};
  16195. for ( const key in this.extensions ) {
  16196. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  16197. }
  16198. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  16199. return data;
  16200. }
  16201. }
  16202. const _position$3 = /*@__PURE__*/ new Vector3();
  16203. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  16204. const _scale$2 = /*@__PURE__*/ new Vector3();
  16205. /**
  16206. * Abstract base class for cameras. This class should always be inherited
  16207. * when you build a new camera.
  16208. *
  16209. * @abstract
  16210. * @augments Object3D
  16211. */
  16212. class Camera extends Object3D {
  16213. /**
  16214. * Constructs a new camera.
  16215. */
  16216. constructor() {
  16217. super();
  16218. /**
  16219. * This flag can be used for type testing.
  16220. *
  16221. * @type {boolean}
  16222. * @readonly
  16223. * @default true
  16224. */
  16225. this.isCamera = true;
  16226. this.type = 'Camera';
  16227. /**
  16228. * The inverse of the camera's world matrix.
  16229. *
  16230. * @type {Matrix4}
  16231. */
  16232. this.matrixWorldInverse = new Matrix4();
  16233. /**
  16234. * The camera's projection matrix.
  16235. *
  16236. * @type {Matrix4}
  16237. */
  16238. this.projectionMatrix = new Matrix4();
  16239. /**
  16240. * The inverse of the camera's projection matrix.
  16241. *
  16242. * @type {Matrix4}
  16243. */
  16244. this.projectionMatrixInverse = new Matrix4();
  16245. /**
  16246. * The coordinate system in which the camera is used.
  16247. *
  16248. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16249. */
  16250. this.coordinateSystem = WebGLCoordinateSystem;
  16251. this._reversedDepth = false;
  16252. }
  16253. /**
  16254. * The flag that indicates whether the camera uses a reversed depth buffer.
  16255. *
  16256. * @type {boolean}
  16257. * @default false
  16258. */
  16259. get reversedDepth() {
  16260. return this._reversedDepth;
  16261. }
  16262. copy( source, recursive ) {
  16263. super.copy( source, recursive );
  16264. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  16265. this.projectionMatrix.copy( source.projectionMatrix );
  16266. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  16267. this.coordinateSystem = source.coordinateSystem;
  16268. return this;
  16269. }
  16270. /**
  16271. * Returns a vector representing the ("look") direction of the 3D object in world space.
  16272. *
  16273. * This method is overwritten since cameras have a different forward vector compared to other
  16274. * 3D objects. A camera looks down its local, negative z-axis by default.
  16275. *
  16276. * @param {Vector3} target - The target vector the result is stored to.
  16277. * @return {Vector3} The 3D object's direction in world space.
  16278. */
  16279. getWorldDirection( target ) {
  16280. return super.getWorldDirection( target ).negate();
  16281. }
  16282. updateMatrixWorld( force ) {
  16283. super.updateMatrixWorld( force );
  16284. // exclude scale from view matrix to be glTF conform
  16285. this.matrixWorld.decompose( _position$3, _quaternion$2, _scale$2 );
  16286. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  16287. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16288. } else {
  16289. this.matrixWorldInverse.compose( _position$3, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  16290. }
  16291. }
  16292. updateWorldMatrix( updateParents, updateChildren ) {
  16293. super.updateWorldMatrix( updateParents, updateChildren );
  16294. // exclude scale from view matrix to be glTF conform
  16295. this.matrixWorld.decompose( _position$3, _quaternion$2, _scale$2 );
  16296. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  16297. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16298. } else {
  16299. this.matrixWorldInverse.compose( _position$3, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  16300. }
  16301. }
  16302. clone() {
  16303. return new this.constructor().copy( this );
  16304. }
  16305. }
  16306. const _v3$1 = /*@__PURE__*/ new Vector3();
  16307. const _minTarget = /*@__PURE__*/ new Vector2();
  16308. const _maxTarget = /*@__PURE__*/ new Vector2();
  16309. /**
  16310. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  16311. *
  16312. * This projection mode is designed to mimic the way the human eye sees. It
  16313. * is the most common projection mode used for rendering a 3D scene.
  16314. *
  16315. * ```js
  16316. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  16317. * scene.add( camera );
  16318. * ```
  16319. *
  16320. * @augments Camera
  16321. */
  16322. class PerspectiveCamera extends Camera {
  16323. /**
  16324. * Constructs a new perspective camera.
  16325. *
  16326. * @param {number} [fov=50] - The vertical field of view.
  16327. * @param {number} [aspect=1] - The aspect ratio.
  16328. * @param {number} [near=0.1] - The camera's near plane.
  16329. * @param {number} [far=2000] - The camera's far plane.
  16330. */
  16331. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  16332. super();
  16333. /**
  16334. * This flag can be used for type testing.
  16335. *
  16336. * @type {boolean}
  16337. * @readonly
  16338. * @default true
  16339. */
  16340. this.isPerspectiveCamera = true;
  16341. this.type = 'PerspectiveCamera';
  16342. /**
  16343. * The vertical field of view, from bottom to top of view,
  16344. * in degrees.
  16345. *
  16346. * @type {number}
  16347. * @default 50
  16348. */
  16349. this.fov = fov;
  16350. /**
  16351. * The zoom factor of the camera.
  16352. *
  16353. * @type {number}
  16354. * @default 1
  16355. */
  16356. this.zoom = 1;
  16357. /**
  16358. * The camera's near plane. The valid range is greater than `0`
  16359. * and less than the current value of {@link PerspectiveCamera#far}.
  16360. *
  16361. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16362. * valid value for a perspective camera's near plane.
  16363. *
  16364. * @type {number}
  16365. * @default 0.1
  16366. */
  16367. this.near = near;
  16368. /**
  16369. * The camera's far plane. Must be greater than the
  16370. * current value of {@link PerspectiveCamera#near}.
  16371. *
  16372. * @type {number}
  16373. * @default 2000
  16374. */
  16375. this.far = far;
  16376. /**
  16377. * Object distance used for stereoscopy and depth-of-field effects. This
  16378. * parameter does not influence the projection matrix unless a
  16379. * {@link StereoCamera} is being used.
  16380. *
  16381. * @type {number}
  16382. * @default 10
  16383. */
  16384. this.focus = 10;
  16385. /**
  16386. * The aspect ratio, usually the canvas width / canvas height.
  16387. *
  16388. * @type {number}
  16389. * @default 1
  16390. */
  16391. this.aspect = aspect;
  16392. /**
  16393. * Represents the frustum window specification. This property should not be edited
  16394. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16395. *
  16396. * @type {?Object}
  16397. * @default null
  16398. */
  16399. this.view = null;
  16400. /**
  16401. * Film size used for the larger axis. Default is `35` (millimeters). This
  16402. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16403. * is set to a nonzero value.
  16404. *
  16405. * @type {number}
  16406. * @default 35
  16407. */
  16408. this.filmGauge = 35;
  16409. /**
  16410. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16411. *
  16412. * @type {number}
  16413. * @default 0
  16414. */
  16415. this.filmOffset = 0;
  16416. this.updateProjectionMatrix();
  16417. }
  16418. copy( source, recursive ) {
  16419. super.copy( source, recursive );
  16420. this.fov = source.fov;
  16421. this.zoom = source.zoom;
  16422. this.near = source.near;
  16423. this.far = source.far;
  16424. this.focus = source.focus;
  16425. this.aspect = source.aspect;
  16426. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16427. this.filmGauge = source.filmGauge;
  16428. this.filmOffset = source.filmOffset;
  16429. return this;
  16430. }
  16431. /**
  16432. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16433. *
  16434. * The default film gauge is 35, so that the focal length can be specified for
  16435. * a 35mm (full frame) camera.
  16436. *
  16437. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16438. */
  16439. setFocalLength( focalLength ) {
  16440. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16441. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16442. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16443. this.updateProjectionMatrix();
  16444. }
  16445. /**
  16446. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16447. * {@link PerspectiveCamera#filmGauge}.
  16448. *
  16449. * @return {number} The computed focal length.
  16450. */
  16451. getFocalLength() {
  16452. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16453. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16454. }
  16455. /**
  16456. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16457. *
  16458. * @return {number} The effective FOV.
  16459. */
  16460. getEffectiveFOV() {
  16461. return RAD2DEG * 2 * Math.atan(
  16462. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16463. }
  16464. /**
  16465. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16466. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16467. *
  16468. * @return {number} The film width.
  16469. */
  16470. getFilmWidth() {
  16471. // film not completely covered in portrait format (aspect < 1)
  16472. return this.filmGauge * Math.min( this.aspect, 1 );
  16473. }
  16474. /**
  16475. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16476. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16477. *
  16478. * @return {number} The film width.
  16479. */
  16480. getFilmHeight() {
  16481. // film not completely covered in landscape format (aspect > 1)
  16482. return this.filmGauge / Math.max( this.aspect, 1 );
  16483. }
  16484. /**
  16485. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16486. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16487. *
  16488. * @param {number} distance - The viewing distance.
  16489. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16490. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16491. */
  16492. getViewBounds( distance, minTarget, maxTarget ) {
  16493. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16494. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16495. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16496. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16497. }
  16498. /**
  16499. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16500. *
  16501. * @param {number} distance - The viewing distance.
  16502. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16503. * @returns {Vector2} The view size.
  16504. */
  16505. getViewSize( distance, target ) {
  16506. this.getViewBounds( distance, _minTarget, _maxTarget );
  16507. return target.subVectors( _maxTarget, _minTarget );
  16508. }
  16509. /**
  16510. * Sets an offset in a larger frustum. This is useful for multi-window or
  16511. * multi-monitor/multi-machine setups.
  16512. *
  16513. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16514. * the monitors are in grid like this
  16515. *```
  16516. * +---+---+---+
  16517. * | A | B | C |
  16518. * +---+---+---+
  16519. * | D | E | F |
  16520. * +---+---+---+
  16521. *```
  16522. * then for each monitor you would call it like this:
  16523. *```js
  16524. * const w = 1920;
  16525. * const h = 1080;
  16526. * const fullWidth = w * 3;
  16527. * const fullHeight = h * 2;
  16528. *
  16529. * // --A--
  16530. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16531. * // --B--
  16532. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16533. * // --C--
  16534. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16535. * // --D--
  16536. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16537. * // --E--
  16538. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16539. * // --F--
  16540. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16541. * ```
  16542. *
  16543. * Note there is no reason monitors have to be the same size or in a grid.
  16544. *
  16545. * @param {number} fullWidth - The full width of multiview setup.
  16546. * @param {number} fullHeight - The full height of multiview setup.
  16547. * @param {number} x - The horizontal offset of the subcamera.
  16548. * @param {number} y - The vertical offset of the subcamera.
  16549. * @param {number} width - The width of subcamera.
  16550. * @param {number} height - The height of subcamera.
  16551. */
  16552. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16553. this.aspect = fullWidth / fullHeight;
  16554. if ( this.view === null ) {
  16555. this.view = {
  16556. enabled: true,
  16557. fullWidth: 1,
  16558. fullHeight: 1,
  16559. offsetX: 0,
  16560. offsetY: 0,
  16561. width: 1,
  16562. height: 1
  16563. };
  16564. }
  16565. this.view.enabled = true;
  16566. this.view.fullWidth = fullWidth;
  16567. this.view.fullHeight = fullHeight;
  16568. this.view.offsetX = x;
  16569. this.view.offsetY = y;
  16570. this.view.width = width;
  16571. this.view.height = height;
  16572. this.updateProjectionMatrix();
  16573. }
  16574. /**
  16575. * Removes the view offset from the projection matrix.
  16576. */
  16577. clearViewOffset() {
  16578. if ( this.view !== null ) {
  16579. this.view.enabled = false;
  16580. }
  16581. this.updateProjectionMatrix();
  16582. }
  16583. /**
  16584. * Updates the camera's projection matrix. Must be called after any change of
  16585. * camera properties.
  16586. */
  16587. updateProjectionMatrix() {
  16588. const near = this.near;
  16589. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16590. let height = 2 * top;
  16591. let width = this.aspect * height;
  16592. let left = -0.5 * width;
  16593. const view = this.view;
  16594. if ( this.view !== null && this.view.enabled ) {
  16595. const fullWidth = view.fullWidth,
  16596. fullHeight = view.fullHeight;
  16597. left += view.offsetX * width / fullWidth;
  16598. top -= view.offsetY * height / fullHeight;
  16599. width *= view.width / fullWidth;
  16600. height *= view.height / fullHeight;
  16601. }
  16602. const skew = this.filmOffset;
  16603. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16604. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16605. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16606. }
  16607. toJSON( meta ) {
  16608. const data = super.toJSON( meta );
  16609. data.object.fov = this.fov;
  16610. data.object.zoom = this.zoom;
  16611. data.object.near = this.near;
  16612. data.object.far = this.far;
  16613. data.object.focus = this.focus;
  16614. data.object.aspect = this.aspect;
  16615. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16616. data.object.filmGauge = this.filmGauge;
  16617. data.object.filmOffset = this.filmOffset;
  16618. return data;
  16619. }
  16620. }
  16621. const fov = -90; // negative fov is not an error
  16622. const aspect = 1;
  16623. /**
  16624. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16625. * cube render target. The render target can then be used as an environment map for rendering
  16626. * realtime reflections in your scene.
  16627. *
  16628. * ```js
  16629. * // Create cube render target
  16630. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16631. *
  16632. * // Create cube camera
  16633. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16634. * scene.add( cubeCamera );
  16635. *
  16636. * // Create car
  16637. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16638. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16639. * scene.add( car );
  16640. *
  16641. * // Update the render target cube
  16642. * car.visible = false;
  16643. * cubeCamera.position.copy( car.position );
  16644. * cubeCamera.update( renderer, scene );
  16645. *
  16646. * // Render the scene
  16647. * car.visible = true;
  16648. * renderer.render( scene, camera );
  16649. * ```
  16650. *
  16651. * @augments Object3D
  16652. */
  16653. class CubeCamera extends Object3D {
  16654. /**
  16655. * Constructs a new cube camera.
  16656. *
  16657. * @param {number} near - The camera's near plane.
  16658. * @param {number} far - The camera's far plane.
  16659. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16660. */
  16661. constructor( near, far, renderTarget ) {
  16662. super();
  16663. this.type = 'CubeCamera';
  16664. /**
  16665. * A reference to the cube render target.
  16666. *
  16667. * @type {WebGLCubeRenderTarget}
  16668. */
  16669. this.renderTarget = renderTarget;
  16670. /**
  16671. * The current active coordinate system.
  16672. *
  16673. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16674. * @default null
  16675. */
  16676. this.coordinateSystem = null;
  16677. /**
  16678. * The current active mipmap level
  16679. *
  16680. * @type {number}
  16681. * @default 0
  16682. */
  16683. this.activeMipmapLevel = 0;
  16684. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16685. cameraPX.layers = this.layers;
  16686. this.add( cameraPX );
  16687. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16688. cameraNX.layers = this.layers;
  16689. this.add( cameraNX );
  16690. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16691. cameraPY.layers = this.layers;
  16692. this.add( cameraPY );
  16693. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16694. cameraNY.layers = this.layers;
  16695. this.add( cameraNY );
  16696. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16697. cameraPZ.layers = this.layers;
  16698. this.add( cameraPZ );
  16699. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16700. cameraNZ.layers = this.layers;
  16701. this.add( cameraNZ );
  16702. }
  16703. /**
  16704. * Must be called when the coordinate system of the cube camera is changed.
  16705. */
  16706. updateCoordinateSystem() {
  16707. const coordinateSystem = this.coordinateSystem;
  16708. const cameras = this.children.concat();
  16709. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16710. for ( const camera of cameras ) this.remove( camera );
  16711. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16712. cameraPX.up.set( 0, 1, 0 );
  16713. cameraPX.lookAt( 1, 0, 0 );
  16714. cameraNX.up.set( 0, 1, 0 );
  16715. cameraNX.lookAt( -1, 0, 0 );
  16716. cameraPY.up.set( 0, 0, -1 );
  16717. cameraPY.lookAt( 0, 1, 0 );
  16718. cameraNY.up.set( 0, 0, 1 );
  16719. cameraNY.lookAt( 0, -1, 0 );
  16720. cameraPZ.up.set( 0, 1, 0 );
  16721. cameraPZ.lookAt( 0, 0, 1 );
  16722. cameraNZ.up.set( 0, 1, 0 );
  16723. cameraNZ.lookAt( 0, 0, -1 );
  16724. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16725. cameraPX.up.set( 0, -1, 0 );
  16726. cameraPX.lookAt( -1, 0, 0 );
  16727. cameraNX.up.set( 0, -1, 0 );
  16728. cameraNX.lookAt( 1, 0, 0 );
  16729. cameraPY.up.set( 0, 0, 1 );
  16730. cameraPY.lookAt( 0, 1, 0 );
  16731. cameraNY.up.set( 0, 0, -1 );
  16732. cameraNY.lookAt( 0, -1, 0 );
  16733. cameraPZ.up.set( 0, -1, 0 );
  16734. cameraPZ.lookAt( 0, 0, 1 );
  16735. cameraNZ.up.set( 0, -1, 0 );
  16736. cameraNZ.lookAt( 0, 0, -1 );
  16737. } else {
  16738. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16739. }
  16740. for ( const camera of cameras ) {
  16741. this.add( camera );
  16742. camera.updateMatrixWorld();
  16743. }
  16744. }
  16745. /**
  16746. * Calling this method will render the given scene with the given renderer
  16747. * into the cube render target of the camera.
  16748. *
  16749. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16750. * @param {Scene} scene - The scene to render.
  16751. */
  16752. update( renderer, scene ) {
  16753. if ( this.parent === null ) this.updateMatrixWorld();
  16754. const { renderTarget, activeMipmapLevel } = this;
  16755. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16756. this.coordinateSystem = renderer.coordinateSystem;
  16757. this.updateCoordinateSystem();
  16758. }
  16759. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16760. const currentRenderTarget = renderer.getRenderTarget();
  16761. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16762. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16763. const currentXrEnabled = renderer.xr.enabled;
  16764. renderer.xr.enabled = false;
  16765. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16766. renderTarget.texture.generateMipmaps = false;
  16767. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  16768. const reversedDepthBuffer = !! ( renderer.isWebGLRenderer && renderer.state.buffers.depth.getReversed() );
  16769. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16770. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  16771. renderer.render( scene, cameraPX );
  16772. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16773. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  16774. renderer.render( scene, cameraNX );
  16775. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16776. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  16777. renderer.render( scene, cameraPY );
  16778. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16779. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  16780. renderer.render( scene, cameraNY );
  16781. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16782. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  16783. renderer.render( scene, cameraPZ );
  16784. // mipmaps are generated during the last call of render()
  16785. // at this point, all sides of the cube render target are defined
  16786. renderTarget.texture.generateMipmaps = generateMipmaps;
  16787. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16788. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  16789. renderer.render( scene, cameraNZ );
  16790. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16791. renderer.xr.enabled = currentXrEnabled;
  16792. renderTarget.texture.needsPMREMUpdate = true;
  16793. }
  16794. }
  16795. /**
  16796. * Creates a cube texture made up of six images.
  16797. *
  16798. * ```js
  16799. * const loader = new THREE.CubeTextureLoader();
  16800. * loader.setPath( 'textures/cube/pisa/' );
  16801. *
  16802. * const textureCube = loader.load( [
  16803. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16804. * ] );
  16805. *
  16806. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16807. * ```
  16808. *
  16809. * @augments Texture
  16810. */
  16811. class CubeTexture extends Texture {
  16812. /**
  16813. * Constructs a new cube texture.
  16814. *
  16815. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16816. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16817. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16818. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16819. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16820. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16821. * @param {number} [format=RGBAFormat] - The texture format.
  16822. * @param {number} [type=UnsignedByteType] - The texture type.
  16823. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16824. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16825. */
  16826. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16827. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16828. /**
  16829. * This flag can be used for type testing.
  16830. *
  16831. * @type {boolean}
  16832. * @readonly
  16833. * @default true
  16834. */
  16835. this.isCubeTexture = true;
  16836. /**
  16837. * If set to `true`, the texture is flipped along the vertical axis when
  16838. * uploaded to the GPU.
  16839. *
  16840. * Overwritten and set to `false` by default.
  16841. *
  16842. * @type {boolean}
  16843. * @default false
  16844. */
  16845. this.flipY = false;
  16846. }
  16847. /**
  16848. * Alias for {@link CubeTexture#image}.
  16849. *
  16850. * @type {Array<Image>}
  16851. */
  16852. get images() {
  16853. return this.image;
  16854. }
  16855. set images( value ) {
  16856. this.image = value;
  16857. }
  16858. }
  16859. /**
  16860. * A cube render target used in context of {@link WebGLRenderer}.
  16861. *
  16862. * @augments WebGLRenderTarget
  16863. */
  16864. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16865. /**
  16866. * Constructs a new cube render target.
  16867. *
  16868. * @param {number} [size=1] - The size of the render target.
  16869. * @param {RenderTarget~Options} [options] - The configuration object.
  16870. */
  16871. constructor( size = 1, options = {} ) {
  16872. super( size, size, options );
  16873. /**
  16874. * This flag can be used for type testing.
  16875. *
  16876. * @type {boolean}
  16877. * @readonly
  16878. * @default true
  16879. */
  16880. this.isWebGLCubeRenderTarget = true;
  16881. const image = { width: size, height: size, depth: 1 };
  16882. const images = [ image, image, image, image, image, image ];
  16883. /**
  16884. * Overwritten with a different texture type.
  16885. *
  16886. * @type {DataArrayTexture}
  16887. */
  16888. this.texture = new CubeTexture( images );
  16889. this._setTextureOptions( options );
  16890. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16891. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16892. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16893. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16894. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16895. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16896. this.texture.isRenderTargetTexture = true;
  16897. }
  16898. /**
  16899. * Converts the given equirectangular texture to a cube map.
  16900. *
  16901. * @param {WebGLRenderer} renderer - The renderer.
  16902. * @param {Texture} texture - The equirectangular texture.
  16903. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16904. */
  16905. fromEquirectangularTexture( renderer, texture ) {
  16906. this.texture.type = texture.type;
  16907. this.texture.colorSpace = texture.colorSpace;
  16908. this.texture.generateMipmaps = texture.generateMipmaps;
  16909. this.texture.minFilter = texture.minFilter;
  16910. this.texture.magFilter = texture.magFilter;
  16911. const shader = {
  16912. uniforms: {
  16913. tEquirect: { value: null },
  16914. },
  16915. vertexShader: /* glsl */`
  16916. varying vec3 vWorldDirection;
  16917. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16918. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16919. }
  16920. void main() {
  16921. vWorldDirection = transformDirection( position, modelMatrix );
  16922. #include <begin_vertex>
  16923. #include <project_vertex>
  16924. }
  16925. `,
  16926. fragmentShader: /* glsl */`
  16927. uniform sampler2D tEquirect;
  16928. varying vec3 vWorldDirection;
  16929. #include <common>
  16930. void main() {
  16931. vec3 direction = normalize( vWorldDirection );
  16932. vec2 sampleUV = equirectUv( direction );
  16933. gl_FragColor = texture2D( tEquirect, sampleUV );
  16934. }
  16935. `
  16936. };
  16937. const geometry = new BoxGeometry( 5, 5, 5 );
  16938. const material = new ShaderMaterial( {
  16939. name: 'CubemapFromEquirect',
  16940. uniforms: cloneUniforms( shader.uniforms ),
  16941. vertexShader: shader.vertexShader,
  16942. fragmentShader: shader.fragmentShader,
  16943. side: BackSide,
  16944. blending: NoBlending
  16945. } );
  16946. material.uniforms.tEquirect.value = texture;
  16947. const mesh = new Mesh( geometry, material );
  16948. const currentMinFilter = texture.minFilter;
  16949. // Avoid blurred poles
  16950. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16951. const camera = new CubeCamera( 1, 10, this );
  16952. camera.update( renderer, mesh );
  16953. texture.minFilter = currentMinFilter;
  16954. mesh.geometry.dispose();
  16955. mesh.material.dispose();
  16956. return this;
  16957. }
  16958. /**
  16959. * Clears this cube render target.
  16960. *
  16961. * @param {WebGLRenderer} renderer - The renderer.
  16962. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16963. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16964. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16965. */
  16966. clear( renderer, color = true, depth = true, stencil = true ) {
  16967. const currentRenderTarget = renderer.getRenderTarget();
  16968. for ( let i = 0; i < 6; i ++ ) {
  16969. renderer.setRenderTarget( this, i );
  16970. renderer.clear( color, depth, stencil );
  16971. }
  16972. renderer.setRenderTarget( currentRenderTarget );
  16973. }
  16974. }
  16975. /**
  16976. * This is almost identical to an {@link Object3D}. Its purpose is to
  16977. * make working with groups of objects syntactically clearer.
  16978. *
  16979. * ```js
  16980. * // Create a group and add the two cubes.
  16981. * // These cubes can now be rotated / scaled etc as a group.
  16982. * const group = new THREE.Group();
  16983. *
  16984. * group.add( meshA );
  16985. * group.add( meshB );
  16986. *
  16987. * scene.add( group );
  16988. * ```
  16989. *
  16990. * @augments Object3D
  16991. */
  16992. class Group extends Object3D {
  16993. constructor() {
  16994. super();
  16995. /**
  16996. * This flag can be used for type testing.
  16997. *
  16998. * @type {boolean}
  16999. * @readonly
  17000. * @default true
  17001. */
  17002. this.isGroup = true;
  17003. this.type = 'Group';
  17004. }
  17005. }
  17006. const _moveEvent = { type: 'move' };
  17007. /**
  17008. * Class for representing a XR controller with its
  17009. * different coordinate systems.
  17010. *
  17011. * @private
  17012. */
  17013. class WebXRController {
  17014. /**
  17015. * Constructs a new XR controller.
  17016. */
  17017. constructor() {
  17018. /**
  17019. * A group representing the target ray space
  17020. * of the XR controller.
  17021. *
  17022. * @private
  17023. * @type {?Group}
  17024. * @default null
  17025. */
  17026. this._targetRay = null;
  17027. /**
  17028. * A group representing the grip space
  17029. * of the XR controller.
  17030. *
  17031. * @private
  17032. * @type {?Group}
  17033. * @default null
  17034. */
  17035. this._grip = null;
  17036. /**
  17037. * A group representing the hand space
  17038. * of the XR controller.
  17039. *
  17040. * @private
  17041. * @type {?Group}
  17042. * @default null
  17043. */
  17044. this._hand = null;
  17045. }
  17046. /**
  17047. * Returns a group representing the hand space of the XR controller.
  17048. *
  17049. * @return {Group} A group representing the hand space of the XR controller.
  17050. */
  17051. getHandSpace() {
  17052. if ( this._hand === null ) {
  17053. this._hand = new Group();
  17054. this._hand.matrixAutoUpdate = false;
  17055. this._hand.visible = false;
  17056. this._hand.joints = {};
  17057. this._hand.inputState = { pinching: false };
  17058. }
  17059. return this._hand;
  17060. }
  17061. /**
  17062. * Returns a group representing the target ray space of the XR controller.
  17063. *
  17064. * @return {Group} A group representing the target ray space of the XR controller.
  17065. */
  17066. getTargetRaySpace() {
  17067. if ( this._targetRay === null ) {
  17068. this._targetRay = new Group();
  17069. this._targetRay.matrixAutoUpdate = false;
  17070. this._targetRay.visible = false;
  17071. this._targetRay.hasLinearVelocity = false;
  17072. this._targetRay.linearVelocity = new Vector3();
  17073. this._targetRay.hasAngularVelocity = false;
  17074. this._targetRay.angularVelocity = new Vector3();
  17075. }
  17076. return this._targetRay;
  17077. }
  17078. /**
  17079. * Returns a group representing the grip space of the XR controller.
  17080. *
  17081. * @return {Group} A group representing the grip space of the XR controller.
  17082. */
  17083. getGripSpace() {
  17084. if ( this._grip === null ) {
  17085. this._grip = new Group();
  17086. this._grip.matrixAutoUpdate = false;
  17087. this._grip.visible = false;
  17088. this._grip.hasLinearVelocity = false;
  17089. this._grip.linearVelocity = new Vector3();
  17090. this._grip.hasAngularVelocity = false;
  17091. this._grip.angularVelocity = new Vector3();
  17092. }
  17093. return this._grip;
  17094. }
  17095. /**
  17096. * Dispatches the given event to the groups representing
  17097. * the different coordinate spaces of the XR controller.
  17098. *
  17099. * @param {Object} event - The event to dispatch.
  17100. * @return {WebXRController} A reference to this instance.
  17101. */
  17102. dispatchEvent( event ) {
  17103. if ( this._targetRay !== null ) {
  17104. this._targetRay.dispatchEvent( event );
  17105. }
  17106. if ( this._grip !== null ) {
  17107. this._grip.dispatchEvent( event );
  17108. }
  17109. if ( this._hand !== null ) {
  17110. this._hand.dispatchEvent( event );
  17111. }
  17112. return this;
  17113. }
  17114. /**
  17115. * Connects the controller with the given XR input source.
  17116. *
  17117. * @param {XRInputSource} inputSource - The input source.
  17118. * @return {WebXRController} A reference to this instance.
  17119. */
  17120. connect( inputSource ) {
  17121. if ( inputSource && inputSource.hand ) {
  17122. const hand = this._hand;
  17123. if ( hand ) {
  17124. for ( const inputjoint of inputSource.hand.values() ) {
  17125. // Initialize hand with joints when connected
  17126. this._getHandJoint( hand, inputjoint );
  17127. }
  17128. }
  17129. }
  17130. this.dispatchEvent( { type: 'connected', data: inputSource } );
  17131. return this;
  17132. }
  17133. /**
  17134. * Disconnects the controller from the given XR input source.
  17135. *
  17136. * @param {XRInputSource} inputSource - The input source.
  17137. * @return {WebXRController} A reference to this instance.
  17138. */
  17139. disconnect( inputSource ) {
  17140. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  17141. if ( this._targetRay !== null ) {
  17142. this._targetRay.visible = false;
  17143. }
  17144. if ( this._grip !== null ) {
  17145. this._grip.visible = false;
  17146. }
  17147. if ( this._hand !== null ) {
  17148. this._hand.visible = false;
  17149. }
  17150. return this;
  17151. }
  17152. /**
  17153. * Updates the controller with the given input source, XR frame and reference space.
  17154. * This updates the transformations of the groups that represent the different
  17155. * coordinate systems of the controller.
  17156. *
  17157. * @param {XRInputSource} inputSource - The input source.
  17158. * @param {XRFrame} frame - The XR frame.
  17159. * @param {XRReferenceSpace} referenceSpace - The reference space.
  17160. * @return {WebXRController} A reference to this instance.
  17161. */
  17162. update( inputSource, frame, referenceSpace ) {
  17163. let inputPose = null;
  17164. let gripPose = null;
  17165. let handPose = null;
  17166. const targetRay = this._targetRay;
  17167. const grip = this._grip;
  17168. const hand = this._hand;
  17169. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  17170. if ( hand && inputSource.hand ) {
  17171. handPose = true;
  17172. for ( const inputjoint of inputSource.hand.values() ) {
  17173. // Update the joints groups with the XRJoint poses
  17174. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  17175. // The transform of this joint will be updated with the joint pose on each frame
  17176. const joint = this._getHandJoint( hand, inputjoint );
  17177. if ( jointPose !== null ) {
  17178. joint.matrix.fromArray( jointPose.transform.matrix );
  17179. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  17180. joint.matrixWorldNeedsUpdate = true;
  17181. joint.jointRadius = jointPose.radius;
  17182. }
  17183. joint.visible = jointPose !== null;
  17184. }
  17185. // Custom events
  17186. // Check pinchz
  17187. const indexTip = hand.joints[ 'index-finger-tip' ];
  17188. const thumbTip = hand.joints[ 'thumb-tip' ];
  17189. const distance = indexTip.position.distanceTo( thumbTip.position );
  17190. const distanceToPinch = 0.02;
  17191. const threshold = 0.005;
  17192. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  17193. hand.inputState.pinching = false;
  17194. this.dispatchEvent( {
  17195. type: 'pinchend',
  17196. handedness: inputSource.handedness,
  17197. target: this
  17198. } );
  17199. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  17200. hand.inputState.pinching = true;
  17201. this.dispatchEvent( {
  17202. type: 'pinchstart',
  17203. handedness: inputSource.handedness,
  17204. target: this
  17205. } );
  17206. }
  17207. } else {
  17208. if ( grip !== null && inputSource.gripSpace ) {
  17209. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  17210. if ( gripPose !== null ) {
  17211. grip.matrix.fromArray( gripPose.transform.matrix );
  17212. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  17213. grip.matrixWorldNeedsUpdate = true;
  17214. if ( gripPose.linearVelocity ) {
  17215. grip.hasLinearVelocity = true;
  17216. grip.linearVelocity.copy( gripPose.linearVelocity );
  17217. } else {
  17218. grip.hasLinearVelocity = false;
  17219. }
  17220. if ( gripPose.angularVelocity ) {
  17221. grip.hasAngularVelocity = true;
  17222. grip.angularVelocity.copy( gripPose.angularVelocity );
  17223. } else {
  17224. grip.hasAngularVelocity = false;
  17225. }
  17226. }
  17227. }
  17228. }
  17229. if ( targetRay !== null ) {
  17230. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  17231. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  17232. if ( inputPose === null && gripPose !== null ) {
  17233. inputPose = gripPose;
  17234. }
  17235. if ( inputPose !== null ) {
  17236. targetRay.matrix.fromArray( inputPose.transform.matrix );
  17237. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  17238. targetRay.matrixWorldNeedsUpdate = true;
  17239. if ( inputPose.linearVelocity ) {
  17240. targetRay.hasLinearVelocity = true;
  17241. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  17242. } else {
  17243. targetRay.hasLinearVelocity = false;
  17244. }
  17245. if ( inputPose.angularVelocity ) {
  17246. targetRay.hasAngularVelocity = true;
  17247. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  17248. } else {
  17249. targetRay.hasAngularVelocity = false;
  17250. }
  17251. this.dispatchEvent( _moveEvent );
  17252. }
  17253. }
  17254. }
  17255. if ( targetRay !== null ) {
  17256. targetRay.visible = ( inputPose !== null );
  17257. }
  17258. if ( grip !== null ) {
  17259. grip.visible = ( gripPose !== null );
  17260. }
  17261. if ( hand !== null ) {
  17262. hand.visible = ( handPose !== null );
  17263. }
  17264. return this;
  17265. }
  17266. /**
  17267. * Returns a group representing the hand joint for the given input joint.
  17268. *
  17269. * @private
  17270. * @param {Group} hand - The group representing the hand space.
  17271. * @param {XRJointSpace} inputjoint - The hand joint data.
  17272. * @return {Group} A group representing the hand joint for the given input joint.
  17273. */
  17274. _getHandJoint( hand, inputjoint ) {
  17275. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  17276. const joint = new Group();
  17277. joint.matrixAutoUpdate = false;
  17278. joint.visible = false;
  17279. hand.joints[ inputjoint.jointName ] = joint;
  17280. hand.add( joint );
  17281. }
  17282. return hand.joints[ inputjoint.jointName ];
  17283. }
  17284. }
  17285. /**
  17286. * This class can be used to define an exponential squared fog,
  17287. * which gives a clear view near the camera and a faster than exponentially
  17288. * densening fog farther from the camera.
  17289. *
  17290. * ```js
  17291. * const scene = new THREE.Scene();
  17292. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  17293. * ```
  17294. */
  17295. class FogExp2 {
  17296. /**
  17297. * Constructs a new fog.
  17298. *
  17299. * @param {number|Color} color - The fog's color.
  17300. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  17301. */
  17302. constructor( color, density = 0.00025 ) {
  17303. /**
  17304. * This flag can be used for type testing.
  17305. *
  17306. * @type {boolean}
  17307. * @readonly
  17308. * @default true
  17309. */
  17310. this.isFogExp2 = true;
  17311. /**
  17312. * The name of the fog.
  17313. *
  17314. * @type {string}
  17315. */
  17316. this.name = '';
  17317. /**
  17318. * The fog's color.
  17319. *
  17320. * @type {Color}
  17321. */
  17322. this.color = new Color( color );
  17323. /**
  17324. * Defines how fast the fog will grow dense.
  17325. *
  17326. * @type {number}
  17327. * @default 0.00025
  17328. */
  17329. this.density = density;
  17330. }
  17331. /**
  17332. * Returns a new fog with copied values from this instance.
  17333. *
  17334. * @return {FogExp2} A clone of this instance.
  17335. */
  17336. clone() {
  17337. return new FogExp2( this.color, this.density );
  17338. }
  17339. /**
  17340. * Serializes the fog into JSON.
  17341. *
  17342. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17343. * @return {Object} A JSON object representing the serialized fog
  17344. */
  17345. toJSON( /* meta */ ) {
  17346. return {
  17347. type: 'FogExp2',
  17348. name: this.name,
  17349. color: this.color.getHex(),
  17350. density: this.density
  17351. };
  17352. }
  17353. }
  17354. /**
  17355. * This class can be used to define a linear fog that grows linearly denser
  17356. * with the distance.
  17357. *
  17358. * ```js
  17359. * const scene = new THREE.Scene();
  17360. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17361. * ```
  17362. */
  17363. class Fog {
  17364. /**
  17365. * Constructs a new fog.
  17366. *
  17367. * @param {number|Color} color - The fog's color.
  17368. * @param {number} [near=1] - The minimum distance to start applying fog.
  17369. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17370. */
  17371. constructor( color, near = 1, far = 1000 ) {
  17372. /**
  17373. * This flag can be used for type testing.
  17374. *
  17375. * @type {boolean}
  17376. * @readonly
  17377. * @default true
  17378. */
  17379. this.isFog = true;
  17380. /**
  17381. * The name of the fog.
  17382. *
  17383. * @type {string}
  17384. */
  17385. this.name = '';
  17386. /**
  17387. * The fog's color.
  17388. *
  17389. * @type {Color}
  17390. */
  17391. this.color = new Color( color );
  17392. /**
  17393. * The minimum distance to start applying fog. Objects that are less than
  17394. * `near` units from the active camera won't be affected by fog.
  17395. *
  17396. * @type {number}
  17397. * @default 1
  17398. */
  17399. this.near = near;
  17400. /**
  17401. * The maximum distance at which fog stops being calculated and applied.
  17402. * Objects that are more than `far` units away from the active camera won't
  17403. * be affected by fog.
  17404. *
  17405. * @type {number}
  17406. * @default 1000
  17407. */
  17408. this.far = far;
  17409. }
  17410. /**
  17411. * Returns a new fog with copied values from this instance.
  17412. *
  17413. * @return {Fog} A clone of this instance.
  17414. */
  17415. clone() {
  17416. return new Fog( this.color, this.near, this.far );
  17417. }
  17418. /**
  17419. * Serializes the fog into JSON.
  17420. *
  17421. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17422. * @return {Object} A JSON object representing the serialized fog
  17423. */
  17424. toJSON( /* meta */ ) {
  17425. return {
  17426. type: 'Fog',
  17427. name: this.name,
  17428. color: this.color.getHex(),
  17429. near: this.near,
  17430. far: this.far
  17431. };
  17432. }
  17433. }
  17434. /**
  17435. * Scenes allow you to set up what is to be rendered and where by three.js.
  17436. * This is where you place 3D objects like meshes, lines or lights.
  17437. *
  17438. * @augments Object3D
  17439. */
  17440. class Scene extends Object3D {
  17441. /**
  17442. * Constructs a new scene.
  17443. */
  17444. constructor() {
  17445. super();
  17446. /**
  17447. * This flag can be used for type testing.
  17448. *
  17449. * @type {boolean}
  17450. * @readonly
  17451. * @default true
  17452. */
  17453. this.isScene = true;
  17454. this.type = 'Scene';
  17455. /**
  17456. * Defines the background of the scene. Valid inputs are:
  17457. *
  17458. * - A color for defining a uniform colored background.
  17459. * - A texture for defining a (flat) textured background.
  17460. * - Cube textures or equirectangular textures for defining a skybox.
  17461. *
  17462. * @type {?(Color|Texture)}
  17463. * @default null
  17464. */
  17465. this.background = null;
  17466. /**
  17467. * Sets the environment map for all physical materials in the scene. However,
  17468. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17469. * material property.
  17470. *
  17471. * @type {?Texture}
  17472. * @default null
  17473. */
  17474. this.environment = null;
  17475. /**
  17476. * A fog instance defining the type of fog that affects everything
  17477. * rendered in the scene.
  17478. *
  17479. * @type {?(Fog|FogExp2)}
  17480. * @default null
  17481. */
  17482. this.fog = null;
  17483. /**
  17484. * Sets the blurriness of the background. Only influences environment maps
  17485. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17486. * and `1`.
  17487. *
  17488. * @type {number}
  17489. * @default 0
  17490. */
  17491. this.backgroundBlurriness = 0;
  17492. /**
  17493. * Attenuates the color of the background. Only applies to background textures.
  17494. *
  17495. * @type {number}
  17496. * @default 1
  17497. */
  17498. this.backgroundIntensity = 1;
  17499. /**
  17500. * The rotation of the background in radians. Only influences environment maps
  17501. * assigned to {@link Scene#background}.
  17502. *
  17503. * @type {Euler}
  17504. * @default (0,0,0)
  17505. */
  17506. this.backgroundRotation = new Euler();
  17507. /**
  17508. * Attenuates the color of the environment. Only influences environment maps
  17509. * assigned to {@link Scene#environment}.
  17510. *
  17511. * @type {number}
  17512. * @default 1
  17513. */
  17514. this.environmentIntensity = 1;
  17515. /**
  17516. * The rotation of the environment map in radians. Only influences physical materials
  17517. * in the scene when {@link Scene#environment} is used.
  17518. *
  17519. * @type {Euler}
  17520. * @default (0,0,0)
  17521. */
  17522. this.environmentRotation = new Euler();
  17523. /**
  17524. * Forces everything in the scene to be rendered with the defined material. It is possible
  17525. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17526. *
  17527. * @type {?Material}
  17528. * @default null
  17529. */
  17530. this.overrideMaterial = null;
  17531. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17532. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17533. }
  17534. }
  17535. copy( source, recursive ) {
  17536. super.copy( source, recursive );
  17537. if ( source.background !== null ) this.background = source.background.clone();
  17538. if ( source.environment !== null ) this.environment = source.environment.clone();
  17539. if ( source.fog !== null ) this.fog = source.fog.clone();
  17540. this.backgroundBlurriness = source.backgroundBlurriness;
  17541. this.backgroundIntensity = source.backgroundIntensity;
  17542. this.backgroundRotation.copy( source.backgroundRotation );
  17543. this.environmentIntensity = source.environmentIntensity;
  17544. this.environmentRotation.copy( source.environmentRotation );
  17545. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17546. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17547. return this;
  17548. }
  17549. toJSON( meta ) {
  17550. const data = super.toJSON( meta );
  17551. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17552. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17553. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17554. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17555. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17556. data.object.environmentRotation = this.environmentRotation.toArray();
  17557. return data;
  17558. }
  17559. }
  17560. /**
  17561. * "Interleaved" means that multiple attributes, possibly of different types,
  17562. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17563. *
  17564. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  17565. */
  17566. class InterleavedBuffer {
  17567. /**
  17568. * Constructs a new interleaved buffer.
  17569. *
  17570. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17571. * @param {number} stride - The number of typed-array elements per vertex.
  17572. */
  17573. constructor( array, stride ) {
  17574. /**
  17575. * This flag can be used for type testing.
  17576. *
  17577. * @type {boolean}
  17578. * @readonly
  17579. * @default true
  17580. */
  17581. this.isInterleavedBuffer = true;
  17582. /**
  17583. * A typed array with a shared buffer storing attribute data.
  17584. *
  17585. * @type {TypedArray}
  17586. */
  17587. this.array = array;
  17588. /**
  17589. * The number of typed-array elements per vertex.
  17590. *
  17591. * @type {number}
  17592. */
  17593. this.stride = stride;
  17594. /**
  17595. * The total number of elements in the array
  17596. *
  17597. * @type {number}
  17598. * @readonly
  17599. */
  17600. this.count = array !== undefined ? array.length / stride : 0;
  17601. /**
  17602. * Defines the intended usage pattern of the data store for optimization purposes.
  17603. *
  17604. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17605. * instantiate a new one and set the desired usage before the next render.
  17606. *
  17607. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17608. * @default StaticDrawUsage
  17609. */
  17610. this.usage = StaticDrawUsage;
  17611. /**
  17612. * This can be used to only update some components of stored vectors (for example, just the
  17613. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17614. *
  17615. * @type {Array<Object>}
  17616. */
  17617. this.updateRanges = [];
  17618. /**
  17619. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17620. *
  17621. * @type {number}
  17622. */
  17623. this.version = 0;
  17624. /**
  17625. * The UUID of the interleaved buffer.
  17626. *
  17627. * @type {string}
  17628. * @readonly
  17629. */
  17630. this.uuid = generateUUID();
  17631. }
  17632. /**
  17633. * A callback function that is executed after the renderer has transferred the attribute array
  17634. * data to the GPU.
  17635. */
  17636. onUploadCallback() {}
  17637. /**
  17638. * Flag to indicate that this attribute has changed and should be re-sent to
  17639. * the GPU. Set this to `true` when you modify the value of the array.
  17640. *
  17641. * @type {number}
  17642. * @default false
  17643. * @param {boolean} value
  17644. */
  17645. set needsUpdate( value ) {
  17646. if ( value === true ) this.version ++;
  17647. }
  17648. /**
  17649. * Sets the usage of this interleaved buffer.
  17650. *
  17651. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17652. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17653. */
  17654. setUsage( value ) {
  17655. this.usage = value;
  17656. return this;
  17657. }
  17658. /**
  17659. * Adds a range of data in the data array to be updated on the GPU.
  17660. *
  17661. * @param {number} start - Position at which to start update.
  17662. * @param {number} count - The number of components to update.
  17663. */
  17664. addUpdateRange( start, count ) {
  17665. this.updateRanges.push( { start, count } );
  17666. }
  17667. /**
  17668. * Clears the update ranges.
  17669. */
  17670. clearUpdateRanges() {
  17671. this.updateRanges.length = 0;
  17672. }
  17673. /**
  17674. * Copies the values of the given interleaved buffer to this instance.
  17675. *
  17676. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17677. * @return {InterleavedBuffer} A reference to this instance.
  17678. */
  17679. copy( source ) {
  17680. this.array = new source.array.constructor( source.array );
  17681. this.count = source.count;
  17682. this.stride = source.stride;
  17683. this.usage = source.usage;
  17684. return this;
  17685. }
  17686. /**
  17687. * Copies a vector from the given interleaved buffer to this one. The start
  17688. * and destination position in the attribute buffers are represented by the
  17689. * given indices.
  17690. *
  17691. * @param {number} index1 - The destination index into this interleaved buffer.
  17692. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17693. * @param {number} index2 - The source index into the given interleaved buffer.
  17694. * @return {InterleavedBuffer} A reference to this instance.
  17695. */
  17696. copyAt( index1, interleavedBuffer, index2 ) {
  17697. index1 *= this.stride;
  17698. index2 *= interleavedBuffer.stride;
  17699. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17700. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17701. }
  17702. return this;
  17703. }
  17704. /**
  17705. * Sets the given array data in the interleaved buffer.
  17706. *
  17707. * @param {(TypedArray|Array)} value - The array data to set.
  17708. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17709. * @return {InterleavedBuffer} A reference to this instance.
  17710. */
  17711. set( value, offset = 0 ) {
  17712. this.array.set( value, offset );
  17713. return this;
  17714. }
  17715. /**
  17716. * Returns a new interleaved buffer with copied values from this instance.
  17717. *
  17718. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17719. * @return {InterleavedBuffer} A clone of this instance.
  17720. */
  17721. clone( data ) {
  17722. if ( data.arrayBuffers === undefined ) {
  17723. data.arrayBuffers = {};
  17724. }
  17725. if ( this.array.buffer._uuid === undefined ) {
  17726. this.array.buffer._uuid = generateUUID();
  17727. }
  17728. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17729. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17730. }
  17731. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17732. const ib = new this.constructor( array, this.stride );
  17733. ib.setUsage( this.usage );
  17734. return ib;
  17735. }
  17736. /**
  17737. * Sets the given callback function that is executed after the Renderer has transferred
  17738. * the array data to the GPU. Can be used to perform clean-up operations after
  17739. * the upload when data are not needed anymore on the CPU side.
  17740. *
  17741. * @param {Function} callback - The `onUpload()` callback.
  17742. * @return {InterleavedBuffer} A reference to this instance.
  17743. */
  17744. onUpload( callback ) {
  17745. this.onUploadCallback = callback;
  17746. return this;
  17747. }
  17748. /**
  17749. * Serializes the interleaved buffer into JSON.
  17750. *
  17751. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17752. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17753. */
  17754. toJSON( data ) {
  17755. if ( data.arrayBuffers === undefined ) {
  17756. data.arrayBuffers = {};
  17757. }
  17758. // generate UUID for array buffer if necessary
  17759. if ( this.array.buffer._uuid === undefined ) {
  17760. this.array.buffer._uuid = generateUUID();
  17761. }
  17762. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17763. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17764. }
  17765. //
  17766. return {
  17767. uuid: this.uuid,
  17768. buffer: this.array.buffer._uuid,
  17769. type: this.array.constructor.name,
  17770. stride: this.stride
  17771. };
  17772. }
  17773. }
  17774. const _vector$7 = /*@__PURE__*/ new Vector3();
  17775. /**
  17776. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17777. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17778. * different offsets into the buffer.
  17779. */
  17780. class InterleavedBufferAttribute {
  17781. /**
  17782. * Constructs a new interleaved buffer attribute.
  17783. *
  17784. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17785. * @param {number} itemSize - The item size.
  17786. * @param {number} offset - The attribute offset into the buffer.
  17787. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17788. */
  17789. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17790. /**
  17791. * This flag can be used for type testing.
  17792. *
  17793. * @type {boolean}
  17794. * @readonly
  17795. * @default true
  17796. */
  17797. this.isInterleavedBufferAttribute = true;
  17798. /**
  17799. * The name of the buffer attribute.
  17800. *
  17801. * @type {string}
  17802. */
  17803. this.name = '';
  17804. /**
  17805. * The buffer holding the interleaved data.
  17806. *
  17807. * @type {InterleavedBuffer}
  17808. */
  17809. this.data = interleavedBuffer;
  17810. /**
  17811. * The item size, see {@link BufferAttribute#itemSize}.
  17812. *
  17813. * @type {number}
  17814. */
  17815. this.itemSize = itemSize;
  17816. /**
  17817. * The attribute offset into the buffer.
  17818. *
  17819. * @type {number}
  17820. */
  17821. this.offset = offset;
  17822. /**
  17823. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17824. *
  17825. * @type {InterleavedBuffer}
  17826. */
  17827. this.normalized = normalized;
  17828. }
  17829. /**
  17830. * The item count of this buffer attribute.
  17831. *
  17832. * @type {number}
  17833. * @readonly
  17834. */
  17835. get count() {
  17836. return this.data.count;
  17837. }
  17838. /**
  17839. * The array holding the interleaved buffer attribute data.
  17840. *
  17841. * @type {TypedArray}
  17842. */
  17843. get array() {
  17844. return this.data.array;
  17845. }
  17846. /**
  17847. * Flag to indicate that this attribute has changed and should be re-sent to
  17848. * the GPU. Set this to `true` when you modify the value of the array.
  17849. *
  17850. * @type {number}
  17851. * @default false
  17852. * @param {boolean} value
  17853. */
  17854. set needsUpdate( value ) {
  17855. this.data.needsUpdate = value;
  17856. }
  17857. /**
  17858. * Applies the given 4x4 matrix to the given attribute. Only works with
  17859. * item size `3`.
  17860. *
  17861. * @param {Matrix4} m - The matrix to apply.
  17862. * @return {InterleavedBufferAttribute} A reference to this instance.
  17863. */
  17864. applyMatrix4( m ) {
  17865. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17866. _vector$7.fromBufferAttribute( this, i );
  17867. _vector$7.applyMatrix4( m );
  17868. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17869. }
  17870. return this;
  17871. }
  17872. /**
  17873. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17874. * item size `3`.
  17875. *
  17876. * @param {Matrix3} m - The normal matrix to apply.
  17877. * @return {InterleavedBufferAttribute} A reference to this instance.
  17878. */
  17879. applyNormalMatrix( m ) {
  17880. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17881. _vector$7.fromBufferAttribute( this, i );
  17882. _vector$7.applyNormalMatrix( m );
  17883. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17884. }
  17885. return this;
  17886. }
  17887. /**
  17888. * Applies the given 4x4 matrix to the given attribute. Only works with
  17889. * item size `3` and with direction vectors.
  17890. *
  17891. * @param {Matrix4} m - The matrix to apply.
  17892. * @return {InterleavedBufferAttribute} A reference to this instance.
  17893. */
  17894. transformDirection( m ) {
  17895. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17896. _vector$7.fromBufferAttribute( this, i );
  17897. _vector$7.transformDirection( m );
  17898. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17899. }
  17900. return this;
  17901. }
  17902. /**
  17903. * Returns the given component of the vector at the given index.
  17904. *
  17905. * @param {number} index - The index into the buffer attribute.
  17906. * @param {number} component - The component index.
  17907. * @return {number} The returned value.
  17908. */
  17909. getComponent( index, component ) {
  17910. let value = this.array[ index * this.data.stride + this.offset + component ];
  17911. if ( this.normalized ) value = denormalize( value, this.array );
  17912. return value;
  17913. }
  17914. /**
  17915. * Sets the given value to the given component of the vector at the given index.
  17916. *
  17917. * @param {number} index - The index into the buffer attribute.
  17918. * @param {number} component - The component index.
  17919. * @param {number} value - The value to set.
  17920. * @return {InterleavedBufferAttribute} A reference to this instance.
  17921. */
  17922. setComponent( index, component, value ) {
  17923. if ( this.normalized ) value = normalize( value, this.array );
  17924. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17925. return this;
  17926. }
  17927. /**
  17928. * Sets the x component of the vector at the given index.
  17929. *
  17930. * @param {number} index - The index into the buffer attribute.
  17931. * @param {number} x - The value to set.
  17932. * @return {InterleavedBufferAttribute} A reference to this instance.
  17933. */
  17934. setX( index, x ) {
  17935. if ( this.normalized ) x = normalize( x, this.array );
  17936. this.data.array[ index * this.data.stride + this.offset ] = x;
  17937. return this;
  17938. }
  17939. /**
  17940. * Sets the y component of the vector at the given index.
  17941. *
  17942. * @param {number} index - The index into the buffer attribute.
  17943. * @param {number} y - The value to set.
  17944. * @return {InterleavedBufferAttribute} A reference to this instance.
  17945. */
  17946. setY( index, y ) {
  17947. if ( this.normalized ) y = normalize( y, this.array );
  17948. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17949. return this;
  17950. }
  17951. /**
  17952. * Sets the z component of the vector at the given index.
  17953. *
  17954. * @param {number} index - The index into the buffer attribute.
  17955. * @param {number} z - The value to set.
  17956. * @return {InterleavedBufferAttribute} A reference to this instance.
  17957. */
  17958. setZ( index, z ) {
  17959. if ( this.normalized ) z = normalize( z, this.array );
  17960. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17961. return this;
  17962. }
  17963. /**
  17964. * Sets the w component of the vector at the given index.
  17965. *
  17966. * @param {number} index - The index into the buffer attribute.
  17967. * @param {number} w - The value to set.
  17968. * @return {InterleavedBufferAttribute} A reference to this instance.
  17969. */
  17970. setW( index, w ) {
  17971. if ( this.normalized ) w = normalize( w, this.array );
  17972. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17973. return this;
  17974. }
  17975. /**
  17976. * Returns the x component of the vector at the given index.
  17977. *
  17978. * @param {number} index - The index into the buffer attribute.
  17979. * @return {number} The x component.
  17980. */
  17981. getX( index ) {
  17982. let x = this.data.array[ index * this.data.stride + this.offset ];
  17983. if ( this.normalized ) x = denormalize( x, this.array );
  17984. return x;
  17985. }
  17986. /**
  17987. * Returns the y component of the vector at the given index.
  17988. *
  17989. * @param {number} index - The index into the buffer attribute.
  17990. * @return {number} The y component.
  17991. */
  17992. getY( index ) {
  17993. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17994. if ( this.normalized ) y = denormalize( y, this.array );
  17995. return y;
  17996. }
  17997. /**
  17998. * Returns the z component of the vector at the given index.
  17999. *
  18000. * @param {number} index - The index into the buffer attribute.
  18001. * @return {number} The z component.
  18002. */
  18003. getZ( index ) {
  18004. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  18005. if ( this.normalized ) z = denormalize( z, this.array );
  18006. return z;
  18007. }
  18008. /**
  18009. * Returns the w component of the vector at the given index.
  18010. *
  18011. * @param {number} index - The index into the buffer attribute.
  18012. * @return {number} The w component.
  18013. */
  18014. getW( index ) {
  18015. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  18016. if ( this.normalized ) w = denormalize( w, this.array );
  18017. return w;
  18018. }
  18019. /**
  18020. * Sets the x and y component of the vector at the given index.
  18021. *
  18022. * @param {number} index - The index into the buffer attribute.
  18023. * @param {number} x - The value for the x component to set.
  18024. * @param {number} y - The value for the y component to set.
  18025. * @return {InterleavedBufferAttribute} A reference to this instance.
  18026. */
  18027. setXY( index, x, y ) {
  18028. index = index * this.data.stride + this.offset;
  18029. if ( this.normalized ) {
  18030. x = normalize( x, this.array );
  18031. y = normalize( y, this.array );
  18032. }
  18033. this.data.array[ index + 0 ] = x;
  18034. this.data.array[ index + 1 ] = y;
  18035. return this;
  18036. }
  18037. /**
  18038. * Sets the x, y and z component of the vector at the given index.
  18039. *
  18040. * @param {number} index - The index into the buffer attribute.
  18041. * @param {number} x - The value for the x component to set.
  18042. * @param {number} y - The value for the y component to set.
  18043. * @param {number} z - The value for the z component to set.
  18044. * @return {InterleavedBufferAttribute} A reference to this instance.
  18045. */
  18046. setXYZ( index, x, y, z ) {
  18047. index = index * this.data.stride + this.offset;
  18048. if ( this.normalized ) {
  18049. x = normalize( x, this.array );
  18050. y = normalize( y, this.array );
  18051. z = normalize( z, this.array );
  18052. }
  18053. this.data.array[ index + 0 ] = x;
  18054. this.data.array[ index + 1 ] = y;
  18055. this.data.array[ index + 2 ] = z;
  18056. return this;
  18057. }
  18058. /**
  18059. * Sets the x, y, z and w component of the vector at the given index.
  18060. *
  18061. * @param {number} index - The index into the buffer attribute.
  18062. * @param {number} x - The value for the x component to set.
  18063. * @param {number} y - The value for the y component to set.
  18064. * @param {number} z - The value for the z component to set.
  18065. * @param {number} w - The value for the w component to set.
  18066. * @return {InterleavedBufferAttribute} A reference to this instance.
  18067. */
  18068. setXYZW( index, x, y, z, w ) {
  18069. index = index * this.data.stride + this.offset;
  18070. if ( this.normalized ) {
  18071. x = normalize( x, this.array );
  18072. y = normalize( y, this.array );
  18073. z = normalize( z, this.array );
  18074. w = normalize( w, this.array );
  18075. }
  18076. this.data.array[ index + 0 ] = x;
  18077. this.data.array[ index + 1 ] = y;
  18078. this.data.array[ index + 2 ] = z;
  18079. this.data.array[ index + 3 ] = w;
  18080. return this;
  18081. }
  18082. /**
  18083. * Returns a new buffer attribute with copied values from this instance.
  18084. *
  18085. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  18086. *
  18087. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  18088. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  18089. */
  18090. clone( data ) {
  18091. if ( data === undefined ) {
  18092. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18093. const array = [];
  18094. for ( let i = 0; i < this.count; i ++ ) {
  18095. const index = i * this.data.stride + this.offset;
  18096. for ( let j = 0; j < this.itemSize; j ++ ) {
  18097. array.push( this.data.array[ index + j ] );
  18098. }
  18099. }
  18100. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18101. } else {
  18102. if ( data.interleavedBuffers === undefined ) {
  18103. data.interleavedBuffers = {};
  18104. }
  18105. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18106. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18107. }
  18108. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18109. }
  18110. }
  18111. /**
  18112. * Serializes the buffer attribute into JSON.
  18113. *
  18114. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  18115. *
  18116. * @param {Object} [data] - An optional value holding meta information about the serialization.
  18117. * @return {Object} A JSON object representing the serialized buffer attribute.
  18118. */
  18119. toJSON( data ) {
  18120. if ( data === undefined ) {
  18121. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18122. const array = [];
  18123. for ( let i = 0; i < this.count; i ++ ) {
  18124. const index = i * this.data.stride + this.offset;
  18125. for ( let j = 0; j < this.itemSize; j ++ ) {
  18126. array.push( this.data.array[ index + j ] );
  18127. }
  18128. }
  18129. // de-interleave data and save it as an ordinary buffer attribute for now
  18130. return {
  18131. itemSize: this.itemSize,
  18132. type: this.array.constructor.name,
  18133. array: array,
  18134. normalized: this.normalized
  18135. };
  18136. } else {
  18137. // save as true interleaved attribute
  18138. if ( data.interleavedBuffers === undefined ) {
  18139. data.interleavedBuffers = {};
  18140. }
  18141. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18142. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18143. }
  18144. return {
  18145. isInterleavedBufferAttribute: true,
  18146. itemSize: this.itemSize,
  18147. data: this.data.uuid,
  18148. offset: this.offset,
  18149. normalized: this.normalized
  18150. };
  18151. }
  18152. }
  18153. }
  18154. /**
  18155. * A material for rendering instances of {@link Sprite}.
  18156. *
  18157. * ```js
  18158. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  18159. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  18160. *
  18161. * const sprite = new THREE.Sprite( material );
  18162. * sprite.scale.set(200, 200, 1)
  18163. * scene.add( sprite );
  18164. * ```
  18165. *
  18166. * @augments Material
  18167. */
  18168. class SpriteMaterial extends Material {
  18169. /**
  18170. * Constructs a new sprite material.
  18171. *
  18172. * @param {Object} [parameters] - An object with one or more properties
  18173. * defining the material's appearance. Any property of the material
  18174. * (including any property from inherited materials) can be passed
  18175. * in here. Color values can be passed any type of value accepted
  18176. * by {@link Color#set}.
  18177. */
  18178. constructor( parameters ) {
  18179. super();
  18180. /**
  18181. * This flag can be used for type testing.
  18182. *
  18183. * @type {boolean}
  18184. * @readonly
  18185. * @default true
  18186. */
  18187. this.isSpriteMaterial = true;
  18188. this.type = 'SpriteMaterial';
  18189. /**
  18190. * Color of the material.
  18191. *
  18192. * @type {Color}
  18193. * @default (1,1,1)
  18194. */
  18195. this.color = new Color( 0xffffff );
  18196. /**
  18197. * The color map. May optionally include an alpha channel, typically combined
  18198. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  18199. * color is modulated by the diffuse `color`.
  18200. *
  18201. * @type {?Texture}
  18202. * @default null
  18203. */
  18204. this.map = null;
  18205. /**
  18206. * The alpha map is a grayscale texture that controls the opacity across the
  18207. * surface (black: fully transparent; white: fully opaque).
  18208. *
  18209. * Only the color of the texture is used, ignoring the alpha channel if one
  18210. * exists. For RGB and RGBA textures, the renderer will use the green channel
  18211. * when sampling this texture due to the extra bit of precision provided for
  18212. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  18213. * luminance/alpha textures will also still work as expected.
  18214. *
  18215. * @type {?Texture}
  18216. * @default null
  18217. */
  18218. this.alphaMap = null;
  18219. /**
  18220. * The rotation of the sprite in radians.
  18221. *
  18222. * @type {number}
  18223. * @default 0
  18224. */
  18225. this.rotation = 0;
  18226. /**
  18227. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  18228. *
  18229. * @type {boolean}
  18230. * @default true
  18231. */
  18232. this.sizeAttenuation = true;
  18233. /**
  18234. * Overwritten since sprite materials are transparent
  18235. * by default.
  18236. *
  18237. * @type {boolean}
  18238. * @default true
  18239. */
  18240. this.transparent = true;
  18241. /**
  18242. * Whether the material is affected by fog or not.
  18243. *
  18244. * @type {boolean}
  18245. * @default true
  18246. */
  18247. this.fog = true;
  18248. this.setValues( parameters );
  18249. }
  18250. copy( source ) {
  18251. super.copy( source );
  18252. this.color.copy( source.color );
  18253. this.map = source.map;
  18254. this.alphaMap = source.alphaMap;
  18255. this.rotation = source.rotation;
  18256. this.sizeAttenuation = source.sizeAttenuation;
  18257. this.fog = source.fog;
  18258. return this;
  18259. }
  18260. }
  18261. let _geometry;
  18262. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18263. const _worldScale = /*@__PURE__*/ new Vector3();
  18264. const _mvPosition = /*@__PURE__*/ new Vector3();
  18265. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18266. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18267. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18268. const _vA = /*@__PURE__*/ new Vector3();
  18269. const _vB = /*@__PURE__*/ new Vector3();
  18270. const _vC = /*@__PURE__*/ new Vector3();
  18271. const _uvA = /*@__PURE__*/ new Vector2();
  18272. const _uvB = /*@__PURE__*/ new Vector2();
  18273. const _uvC = /*@__PURE__*/ new Vector2();
  18274. /**
  18275. * A sprite is a plane that always faces towards the camera, generally with a
  18276. * partially transparent texture applied.
  18277. *
  18278. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  18279. * have no effect.
  18280. *
  18281. * ```js
  18282. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  18283. * const material = new THREE.SpriteMaterial( { map: map } );
  18284. *
  18285. * const sprite = new THREE.Sprite( material );
  18286. * scene.add( sprite );
  18287. * ```
  18288. *
  18289. * @augments Object3D
  18290. */
  18291. class Sprite extends Object3D {
  18292. /**
  18293. * Constructs a new sprite.
  18294. *
  18295. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  18296. */
  18297. constructor( material = new SpriteMaterial() ) {
  18298. super();
  18299. /**
  18300. * This flag can be used for type testing.
  18301. *
  18302. * @type {boolean}
  18303. * @readonly
  18304. * @default true
  18305. */
  18306. this.isSprite = true;
  18307. this.type = 'Sprite';
  18308. if ( _geometry === undefined ) {
  18309. _geometry = new BufferGeometry();
  18310. const float32Array = new Float32Array( [
  18311. -0.5, -0.5, 0, 0, 0,
  18312. 0.5, -0.5, 0, 1, 0,
  18313. 0.5, 0.5, 0, 1, 1,
  18314. -0.5, 0.5, 0, 0, 1
  18315. ] );
  18316. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18317. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18318. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18319. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18320. }
  18321. /**
  18322. * The sprite geometry.
  18323. *
  18324. * @type {BufferGeometry}
  18325. */
  18326. this.geometry = _geometry;
  18327. /**
  18328. * The sprite material.
  18329. *
  18330. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  18331. */
  18332. this.material = material;
  18333. /**
  18334. * The sprite's anchor point, and the point around which the sprite rotates.
  18335. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  18336. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  18337. *
  18338. * @type {Vector2}
  18339. * @default (0.5,0.5)
  18340. */
  18341. this.center = new Vector2( 0.5, 0.5 );
  18342. /**
  18343. * The number of instances of this sprite.
  18344. * Can only be used with {@link WebGPURenderer}.
  18345. *
  18346. * @type {number}
  18347. * @default 1
  18348. */
  18349. this.count = 1;
  18350. }
  18351. /**
  18352. * Computes intersection points between a casted ray and this sprite.
  18353. *
  18354. * @param {Raycaster} raycaster - The raycaster.
  18355. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18356. */
  18357. raycast( raycaster, intersects ) {
  18358. if ( raycaster.camera === null ) {
  18359. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18360. }
  18361. _worldScale.setFromMatrixScale( this.matrixWorld );
  18362. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18363. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18364. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18365. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18366. _worldScale.multiplyScalar( - _mvPosition.z );
  18367. }
  18368. const rotation = this.material.rotation;
  18369. let sin, cos;
  18370. if ( rotation !== 0 ) {
  18371. cos = Math.cos( rotation );
  18372. sin = Math.sin( rotation );
  18373. }
  18374. const center = this.center;
  18375. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18376. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18377. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18378. _uvA.set( 0, 0 );
  18379. _uvB.set( 1, 0 );
  18380. _uvC.set( 1, 1 );
  18381. // check first triangle
  18382. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18383. if ( intersect === null ) {
  18384. // check second triangle
  18385. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18386. _uvB.set( 0, 1 );
  18387. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18388. if ( intersect === null ) {
  18389. return;
  18390. }
  18391. }
  18392. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18393. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18394. intersects.push( {
  18395. distance: distance,
  18396. point: _intersectPoint.clone(),
  18397. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18398. face: null,
  18399. object: this
  18400. } );
  18401. }
  18402. copy( source, recursive ) {
  18403. super.copy( source, recursive );
  18404. if ( source.center !== undefined ) this.center.copy( source.center );
  18405. this.material = source.material;
  18406. return this;
  18407. }
  18408. }
  18409. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18410. // compute position in camera space
  18411. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18412. // to check if rotation is not zero
  18413. if ( sin !== undefined ) {
  18414. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18415. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18416. } else {
  18417. _rotatedPosition.copy( _alignedPosition );
  18418. }
  18419. vertexPosition.copy( mvPosition );
  18420. vertexPosition.x += _rotatedPosition.x;
  18421. vertexPosition.y += _rotatedPosition.y;
  18422. // transform to world space
  18423. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18424. }
  18425. const _v1$2 = /*@__PURE__*/ new Vector3();
  18426. const _v2$1 = /*@__PURE__*/ new Vector3();
  18427. /**
  18428. * A component for providing a basic Level of Detail (LOD) mechanism.
  18429. *
  18430. * Every LOD level is associated with an object, and rendering can be switched
  18431. * between them at the distances specified. Typically you would create, say,
  18432. * three meshes, one for far away (low detail), one for mid range (medium
  18433. * detail) and one for close up (high detail).
  18434. *
  18435. * ```js
  18436. * const lod = new THREE.LOD();
  18437. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18438. *
  18439. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18440. * for( let i = 0; i < 3; i++ ) {
  18441. *
  18442. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18443. * const mesh = new THREE.Mesh( geometry, material );
  18444. * lod.addLevel( mesh, i * 75 );
  18445. *
  18446. * }
  18447. *
  18448. * scene.add( lod );
  18449. * ```
  18450. *
  18451. * @augments Object3D
  18452. */
  18453. class LOD extends Object3D {
  18454. /**
  18455. * Constructs a new LOD.
  18456. */
  18457. constructor() {
  18458. super();
  18459. /**
  18460. * This flag can be used for type testing.
  18461. *
  18462. * @type {boolean}
  18463. * @readonly
  18464. * @default true
  18465. */
  18466. this.isLOD = true;
  18467. /**
  18468. * The current LOD index.
  18469. *
  18470. * @private
  18471. * @type {number}
  18472. * @default 0
  18473. */
  18474. this._currentLevel = 0;
  18475. this.type = 'LOD';
  18476. Object.defineProperties( this, {
  18477. /**
  18478. * This array holds the LOD levels.
  18479. *
  18480. * @name LOD#levels
  18481. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18482. */
  18483. levels: {
  18484. enumerable: true,
  18485. value: []
  18486. }
  18487. } );
  18488. /**
  18489. * Whether the LOD object is updated automatically by the renderer per frame
  18490. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18491. * render loop by yourself.
  18492. *
  18493. * @type {boolean}
  18494. * @default true
  18495. */
  18496. this.autoUpdate = true;
  18497. }
  18498. copy( source ) {
  18499. super.copy( source, false );
  18500. const levels = source.levels;
  18501. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18502. const level = levels[ i ];
  18503. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18504. }
  18505. this.autoUpdate = source.autoUpdate;
  18506. return this;
  18507. }
  18508. /**
  18509. * Adds a mesh that will display at a certain distance and greater. Typically
  18510. * the further away the distance, the lower the detail on the mesh.
  18511. *
  18512. * @param {Object3D} object - The 3D object to display at this level.
  18513. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18514. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18515. * @return {LOD} A reference to this instance.
  18516. */
  18517. addLevel( object, distance = 0, hysteresis = 0 ) {
  18518. distance = Math.abs( distance );
  18519. const levels = this.levels;
  18520. let l;
  18521. for ( l = 0; l < levels.length; l ++ ) {
  18522. if ( distance < levels[ l ].distance ) {
  18523. break;
  18524. }
  18525. }
  18526. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18527. this.add( object );
  18528. return this;
  18529. }
  18530. /**
  18531. * Removes an existing level, based on the distance from the camera.
  18532. * Returns `true` when the level has been removed. Otherwise `false`.
  18533. *
  18534. * @param {number} distance - Distance of the level to remove.
  18535. * @return {boolean} Whether the level has been removed or not.
  18536. */
  18537. removeLevel( distance ) {
  18538. const levels = this.levels;
  18539. for ( let i = 0; i < levels.length; i ++ ) {
  18540. if ( levels[ i ].distance === distance ) {
  18541. const removedElements = levels.splice( i, 1 );
  18542. this.remove( removedElements[ 0 ].object );
  18543. return true;
  18544. }
  18545. }
  18546. return false;
  18547. }
  18548. /**
  18549. * Returns the currently active LOD level index.
  18550. *
  18551. * @return {number} The current active LOD level index.
  18552. */
  18553. getCurrentLevel() {
  18554. return this._currentLevel;
  18555. }
  18556. /**
  18557. * Returns a reference to the first 3D object that is greater than
  18558. * the given distance.
  18559. *
  18560. * @param {number} distance - The LOD distance.
  18561. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  18562. */
  18563. getObjectForDistance( distance ) {
  18564. const levels = this.levels;
  18565. if ( levels.length > 0 ) {
  18566. let i, l;
  18567. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18568. let levelDistance = levels[ i ].distance;
  18569. if ( levels[ i ].object.visible ) {
  18570. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18571. }
  18572. if ( distance < levelDistance ) {
  18573. break;
  18574. }
  18575. }
  18576. return levels[ i - 1 ].object;
  18577. }
  18578. return null;
  18579. }
  18580. /**
  18581. * Computes intersection points between a casted ray and this LOD.
  18582. *
  18583. * @param {Raycaster} raycaster - The raycaster.
  18584. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18585. */
  18586. raycast( raycaster, intersects ) {
  18587. const levels = this.levels;
  18588. if ( levels.length > 0 ) {
  18589. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18590. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18591. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18592. }
  18593. }
  18594. /**
  18595. * Updates the LOD by computing which LOD level should be visible according
  18596. * to the current distance of the given camera.
  18597. *
  18598. * @param {Camera} camera - The camera the scene is rendered with.
  18599. */
  18600. update( camera ) {
  18601. const levels = this.levels;
  18602. if ( levels.length > 1 ) {
  18603. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18604. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18605. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18606. levels[ 0 ].object.visible = true;
  18607. let i, l;
  18608. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18609. let levelDistance = levels[ i ].distance;
  18610. if ( levels[ i ].object.visible ) {
  18611. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18612. }
  18613. if ( distance >= levelDistance ) {
  18614. levels[ i - 1 ].object.visible = false;
  18615. levels[ i ].object.visible = true;
  18616. } else {
  18617. break;
  18618. }
  18619. }
  18620. this._currentLevel = i - 1;
  18621. for ( ; i < l; i ++ ) {
  18622. levels[ i ].object.visible = false;
  18623. }
  18624. }
  18625. }
  18626. toJSON( meta ) {
  18627. const data = super.toJSON( meta );
  18628. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18629. data.object.levels = [];
  18630. const levels = this.levels;
  18631. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18632. const level = levels[ i ];
  18633. data.object.levels.push( {
  18634. object: level.object.uuid,
  18635. distance: level.distance,
  18636. hysteresis: level.hysteresis
  18637. } );
  18638. }
  18639. return data;
  18640. }
  18641. }
  18642. const _basePosition = /*@__PURE__*/ new Vector3();
  18643. const _skinIndex = /*@__PURE__*/ new Vector4();
  18644. const _skinWeight = /*@__PURE__*/ new Vector4();
  18645. const _vector3 = /*@__PURE__*/ new Vector3();
  18646. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18647. const _vertex = /*@__PURE__*/ new Vector3();
  18648. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18649. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18650. const _ray$2 = /*@__PURE__*/ new Ray();
  18651. /**
  18652. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18653. * vertices of the geometry with skinning/skeleton animation.
  18654. *
  18655. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18656. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18657. * vertex to a certain extend.
  18658. *
  18659. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18660. * or {@link FBXLoader } import respective models.
  18661. *
  18662. * @augments Mesh
  18663. * @demo scenes/bones-browser.html
  18664. */
  18665. class SkinnedMesh extends Mesh {
  18666. /**
  18667. * Constructs a new skinned mesh.
  18668. *
  18669. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18670. * @param {Material|Array<Material>} [material] - The mesh material.
  18671. */
  18672. constructor( geometry, material ) {
  18673. super( geometry, material );
  18674. /**
  18675. * This flag can be used for type testing.
  18676. *
  18677. * @type {boolean}
  18678. * @readonly
  18679. * @default true
  18680. */
  18681. this.isSkinnedMesh = true;
  18682. this.type = 'SkinnedMesh';
  18683. /**
  18684. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18685. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18686. * across multiple skinned meshes.
  18687. *
  18688. * @type {(AttachedBindMode|DetachedBindMode)}
  18689. * @default AttachedBindMode
  18690. */
  18691. this.bindMode = AttachedBindMode;
  18692. /**
  18693. * The base matrix that is used for the bound bone transforms.
  18694. *
  18695. * @type {Matrix4}
  18696. */
  18697. this.bindMatrix = new Matrix4();
  18698. /**
  18699. * The base matrix that is used for resetting the bound bone transforms.
  18700. *
  18701. * @type {Matrix4}
  18702. */
  18703. this.bindMatrixInverse = new Matrix4();
  18704. /**
  18705. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18706. *
  18707. * @type {?Box3}
  18708. * @default null
  18709. */
  18710. this.boundingBox = null;
  18711. /**
  18712. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18713. *
  18714. * @type {?Sphere}
  18715. * @default null
  18716. */
  18717. this.boundingSphere = null;
  18718. }
  18719. /**
  18720. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18721. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18722. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18723. * the current animation state.
  18724. */
  18725. computeBoundingBox() {
  18726. const geometry = this.geometry;
  18727. if ( this.boundingBox === null ) {
  18728. this.boundingBox = new Box3();
  18729. }
  18730. this.boundingBox.makeEmpty();
  18731. const positionAttribute = geometry.getAttribute( 'position' );
  18732. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18733. this.getVertexPosition( i, _vertex );
  18734. this.boundingBox.expandByPoint( _vertex );
  18735. }
  18736. }
  18737. /**
  18738. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18739. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18740. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18741. * per frame in order to reflect the current animation state.
  18742. */
  18743. computeBoundingSphere() {
  18744. const geometry = this.geometry;
  18745. if ( this.boundingSphere === null ) {
  18746. this.boundingSphere = new Sphere();
  18747. }
  18748. this.boundingSphere.makeEmpty();
  18749. const positionAttribute = geometry.getAttribute( 'position' );
  18750. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18751. this.getVertexPosition( i, _vertex );
  18752. this.boundingSphere.expandByPoint( _vertex );
  18753. }
  18754. }
  18755. copy( source, recursive ) {
  18756. super.copy( source, recursive );
  18757. this.bindMode = source.bindMode;
  18758. this.bindMatrix.copy( source.bindMatrix );
  18759. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18760. this.skeleton = source.skeleton;
  18761. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18762. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18763. return this;
  18764. }
  18765. raycast( raycaster, intersects ) {
  18766. const material = this.material;
  18767. const matrixWorld = this.matrixWorld;
  18768. if ( material === undefined ) return;
  18769. // test with bounding sphere in world space
  18770. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18771. _sphere$5.copy( this.boundingSphere );
  18772. _sphere$5.applyMatrix4( matrixWorld );
  18773. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18774. // convert ray to local space of skinned mesh
  18775. _inverseMatrix$2.copy( matrixWorld ).invert();
  18776. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18777. // test with bounding box in local space
  18778. if ( this.boundingBox !== null ) {
  18779. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18780. }
  18781. // test for intersections with geometry
  18782. this._computeIntersections( raycaster, intersects, _ray$2 );
  18783. }
  18784. getVertexPosition( index, target ) {
  18785. super.getVertexPosition( index, target );
  18786. this.applyBoneTransform( index, target );
  18787. return target;
  18788. }
  18789. /**
  18790. * Binds the given skeleton to the skinned mesh.
  18791. *
  18792. * @param {Skeleton} skeleton - The skeleton to bind.
  18793. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18794. * the skinned mesh's world matrix will be used instead.
  18795. */
  18796. bind( skeleton, bindMatrix ) {
  18797. this.skeleton = skeleton;
  18798. if ( bindMatrix === undefined ) {
  18799. this.updateMatrixWorld( true );
  18800. this.skeleton.calculateInverses();
  18801. bindMatrix = this.matrixWorld;
  18802. }
  18803. this.bindMatrix.copy( bindMatrix );
  18804. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18805. }
  18806. /**
  18807. * This method sets the skinned mesh in the rest pose).
  18808. */
  18809. pose() {
  18810. this.skeleton.pose();
  18811. }
  18812. /**
  18813. * Normalizes the skin weights which are defined as a buffer attribute
  18814. * in the skinned mesh's geometry.
  18815. */
  18816. normalizeSkinWeights() {
  18817. const vector = new Vector4();
  18818. const skinWeight = this.geometry.attributes.skinWeight;
  18819. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18820. vector.fromBufferAttribute( skinWeight, i );
  18821. const scale = 1.0 / vector.manhattanLength();
  18822. if ( scale !== Infinity ) {
  18823. vector.multiplyScalar( scale );
  18824. } else {
  18825. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18826. }
  18827. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18828. }
  18829. }
  18830. updateMatrixWorld( force ) {
  18831. super.updateMatrixWorld( force );
  18832. if ( this.bindMode === AttachedBindMode ) {
  18833. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18834. } else if ( this.bindMode === DetachedBindMode ) {
  18835. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18836. } else {
  18837. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18838. }
  18839. }
  18840. /**
  18841. * Applies the bone transform associated with the given index to the given
  18842. * vertex position. Returns the updated vector.
  18843. *
  18844. * @param {number} index - The vertex index.
  18845. * @param {Vector3} target - The target object that is used to store the method's result.
  18846. * the skinned mesh's world matrix will be used instead.
  18847. * @return {Vector3} The updated vertex position.
  18848. */
  18849. applyBoneTransform( index, target ) {
  18850. const skeleton = this.skeleton;
  18851. const geometry = this.geometry;
  18852. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18853. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18854. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18855. target.set( 0, 0, 0 );
  18856. for ( let i = 0; i < 4; i ++ ) {
  18857. const weight = _skinWeight.getComponent( i );
  18858. if ( weight !== 0 ) {
  18859. const boneIndex = _skinIndex.getComponent( i );
  18860. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18861. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18862. }
  18863. }
  18864. return target.applyMatrix4( this.bindMatrixInverse );
  18865. }
  18866. }
  18867. /**
  18868. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18869. * the {@link SkinnedMesh}.
  18870. *
  18871. * ```js
  18872. * const root = new THREE.Bone();
  18873. * const child = new THREE.Bone();
  18874. *
  18875. * root.add( child );
  18876. * child.position.y = 5;
  18877. * ```
  18878. *
  18879. * @augments Object3D
  18880. */
  18881. class Bone extends Object3D {
  18882. /**
  18883. * Constructs a new bone.
  18884. */
  18885. constructor() {
  18886. super();
  18887. /**
  18888. * This flag can be used for type testing.
  18889. *
  18890. * @type {boolean}
  18891. * @readonly
  18892. * @default true
  18893. */
  18894. this.isBone = true;
  18895. this.type = 'Bone';
  18896. }
  18897. }
  18898. /**
  18899. * Creates a texture directly from raw buffer data.
  18900. *
  18901. * The interpretation of the data depends on type and format: If the type is
  18902. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18903. * texel data. If the format is `RGBAFormat`, data needs four values for
  18904. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18905. *
  18906. * @augments Texture
  18907. */
  18908. class DataTexture extends Texture {
  18909. /**
  18910. * Constructs a new data texture.
  18911. *
  18912. * @param {?TypedArray} [data=null] - The buffer data.
  18913. * @param {number} [width=1] - The width of the texture.
  18914. * @param {number} [height=1] - The height of the texture.
  18915. * @param {number} [format=RGBAFormat] - The texture format.
  18916. * @param {number} [type=UnsignedByteType] - The texture type.
  18917. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18918. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18919. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18920. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18921. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18922. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18923. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18924. */
  18925. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18926. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18927. /**
  18928. * This flag can be used for type testing.
  18929. *
  18930. * @type {boolean}
  18931. * @readonly
  18932. * @default true
  18933. */
  18934. this.isDataTexture = true;
  18935. /**
  18936. * The image definition of a data texture.
  18937. *
  18938. * @type {{data:TypedArray,width:number,height:number}}
  18939. */
  18940. this.image = { data: data, width: width, height: height };
  18941. /**
  18942. * Whether to generate mipmaps (if possible) for a texture.
  18943. *
  18944. * Overwritten and set to `false` by default.
  18945. *
  18946. * @type {boolean}
  18947. * @default false
  18948. */
  18949. this.generateMipmaps = false;
  18950. /**
  18951. * If set to `true`, the texture is flipped along the vertical axis when
  18952. * uploaded to the GPU.
  18953. *
  18954. * Overwritten and set to `false` by default.
  18955. *
  18956. * @type {boolean}
  18957. * @default false
  18958. */
  18959. this.flipY = false;
  18960. /**
  18961. * Specifies the alignment requirements for the start of each pixel row in memory.
  18962. *
  18963. * Overwritten and set to `1` by default.
  18964. *
  18965. * @type {boolean}
  18966. * @default 1
  18967. */
  18968. this.unpackAlignment = 1;
  18969. }
  18970. }
  18971. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18972. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18973. /**
  18974. * Class for representing the armatures in `three.js`. The skeleton
  18975. * is defined by a hierarchy of bones.
  18976. *
  18977. * ```js
  18978. * const bones = [];
  18979. *
  18980. * const shoulder = new THREE.Bone();
  18981. * const elbow = new THREE.Bone();
  18982. * const hand = new THREE.Bone();
  18983. *
  18984. * shoulder.add( elbow );
  18985. * elbow.add( hand );
  18986. *
  18987. * bones.push( shoulder , elbow, hand);
  18988. *
  18989. * shoulder.position.y = -5;
  18990. * elbow.position.y = 0;
  18991. * hand.position.y = 5;
  18992. *
  18993. * const armSkeleton = new THREE.Skeleton( bones );
  18994. * ```
  18995. */
  18996. class Skeleton {
  18997. /**
  18998. * Constructs a new skeleton.
  18999. *
  19000. * @param {Array<Bone>} [bones] - An array of bones.
  19001. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  19002. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  19003. */
  19004. constructor( bones = [], boneInverses = [] ) {
  19005. this.uuid = generateUUID();
  19006. /**
  19007. * An array of bones defining the skeleton.
  19008. *
  19009. * @type {Array<Bone>}
  19010. */
  19011. this.bones = bones.slice( 0 );
  19012. /**
  19013. * An array of bone inverse matrices.
  19014. *
  19015. * @type {Array<Matrix4>}
  19016. */
  19017. this.boneInverses = boneInverses;
  19018. /**
  19019. * An array buffer holding the bone data.
  19020. * Input data for {@link Skeleton#boneTexture}.
  19021. *
  19022. * @type {?Float32Array}
  19023. * @default null
  19024. */
  19025. this.boneMatrices = null;
  19026. /**
  19027. * An array buffer holding the bone data of the previous frame.
  19028. * Required for computing velocity. Maintained in {@link SkinningNode}.
  19029. *
  19030. * @type {?Float32Array}
  19031. * @default null
  19032. */
  19033. this.previousBoneMatrices = null;
  19034. /**
  19035. * A texture holding the bone data for use
  19036. * in the vertex shader.
  19037. *
  19038. * @type {?DataTexture}
  19039. * @default null
  19040. */
  19041. this.boneTexture = null;
  19042. this.init();
  19043. }
  19044. /**
  19045. * Initializes the skeleton. This method gets automatically called by the constructor
  19046. * but depending on how the skeleton is created it might be necessary to call this method
  19047. * manually.
  19048. */
  19049. init() {
  19050. const bones = this.bones;
  19051. const boneInverses = this.boneInverses;
  19052. this.boneMatrices = new Float32Array( bones.length * 16 );
  19053. // calculate inverse bone matrices if necessary
  19054. if ( boneInverses.length === 0 ) {
  19055. this.calculateInverses();
  19056. } else {
  19057. // handle special case
  19058. if ( bones.length !== boneInverses.length ) {
  19059. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  19060. this.boneInverses = [];
  19061. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19062. this.boneInverses.push( new Matrix4() );
  19063. }
  19064. }
  19065. }
  19066. }
  19067. /**
  19068. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  19069. * and fills it with new matrices.
  19070. */
  19071. calculateInverses() {
  19072. this.boneInverses.length = 0;
  19073. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19074. const inverse = new Matrix4();
  19075. if ( this.bones[ i ] ) {
  19076. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  19077. }
  19078. this.boneInverses.push( inverse );
  19079. }
  19080. }
  19081. /**
  19082. * Resets the skeleton to the base pose.
  19083. */
  19084. pose() {
  19085. // recover the bind-time world matrices
  19086. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19087. const bone = this.bones[ i ];
  19088. if ( bone ) {
  19089. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  19090. }
  19091. }
  19092. // compute the local matrices, positions, rotations and scales
  19093. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19094. const bone = this.bones[ i ];
  19095. if ( bone ) {
  19096. if ( bone.parent && bone.parent.isBone ) {
  19097. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  19098. bone.matrix.multiply( bone.matrixWorld );
  19099. } else {
  19100. bone.matrix.copy( bone.matrixWorld );
  19101. }
  19102. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  19103. }
  19104. }
  19105. }
  19106. /**
  19107. * Resets the skeleton to the base pose.
  19108. */
  19109. update() {
  19110. const bones = this.bones;
  19111. const boneInverses = this.boneInverses;
  19112. const boneMatrices = this.boneMatrices;
  19113. const boneTexture = this.boneTexture;
  19114. // flatten bone matrices to array
  19115. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  19116. // compute the offset between the current and the original transform
  19117. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  19118. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  19119. _offsetMatrix.toArray( boneMatrices, i * 16 );
  19120. }
  19121. if ( boneTexture !== null ) {
  19122. boneTexture.needsUpdate = true;
  19123. }
  19124. }
  19125. /**
  19126. * Returns a new skeleton with copied values from this instance.
  19127. *
  19128. * @return {Skeleton} A clone of this instance.
  19129. */
  19130. clone() {
  19131. return new Skeleton( this.bones, this.boneInverses );
  19132. }
  19133. /**
  19134. * Computes a data texture for passing bone data to the vertex shader.
  19135. *
  19136. * @return {Skeleton} A reference of this instance.
  19137. */
  19138. computeBoneTexture() {
  19139. // layout (1 matrix = 4 pixels)
  19140. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19141. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19142. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19143. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19144. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19145. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  19146. size = Math.ceil( size / 4 ) * 4;
  19147. size = Math.max( size, 4 );
  19148. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19149. boneMatrices.set( this.boneMatrices ); // copy current values
  19150. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19151. boneTexture.needsUpdate = true;
  19152. this.boneMatrices = boneMatrices;
  19153. this.boneTexture = boneTexture;
  19154. return this;
  19155. }
  19156. /**
  19157. * Searches through the skeleton's bone array and returns the first with a
  19158. * matching name.
  19159. *
  19160. * @param {string} name - The name of the bone.
  19161. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  19162. */
  19163. getBoneByName( name ) {
  19164. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19165. const bone = this.bones[ i ];
  19166. if ( bone.name === name ) {
  19167. return bone;
  19168. }
  19169. }
  19170. return undefined;
  19171. }
  19172. /**
  19173. * Frees the GPU-related resources allocated by this instance. Call this
  19174. * method whenever this instance is no longer used in your app.
  19175. */
  19176. dispose( ) {
  19177. if ( this.boneTexture !== null ) {
  19178. this.boneTexture.dispose();
  19179. this.boneTexture = null;
  19180. }
  19181. }
  19182. /**
  19183. * Setups the skeleton by the given JSON and bones.
  19184. *
  19185. * @param {Object} json - The skeleton as serialized JSON.
  19186. * @param {Object<string, Bone>} bones - An array of bones.
  19187. * @return {Skeleton} A reference of this instance.
  19188. */
  19189. fromJSON( json, bones ) {
  19190. this.uuid = json.uuid;
  19191. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  19192. const uuid = json.bones[ i ];
  19193. let bone = bones[ uuid ];
  19194. if ( bone === undefined ) {
  19195. warn( 'Skeleton: No bone found with UUID:', uuid );
  19196. bone = new Bone();
  19197. }
  19198. this.bones.push( bone );
  19199. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  19200. }
  19201. this.init();
  19202. return this;
  19203. }
  19204. /**
  19205. * Serializes the skeleton into JSON.
  19206. *
  19207. * @return {Object} A JSON object representing the serialized skeleton.
  19208. * @see {@link ObjectLoader#parse}
  19209. */
  19210. toJSON() {
  19211. const data = {
  19212. metadata: {
  19213. version: 4.7,
  19214. type: 'Skeleton',
  19215. generator: 'Skeleton.toJSON'
  19216. },
  19217. bones: [],
  19218. boneInverses: []
  19219. };
  19220. data.uuid = this.uuid;
  19221. const bones = this.bones;
  19222. const boneInverses = this.boneInverses;
  19223. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19224. const bone = bones[ i ];
  19225. data.bones.push( bone.uuid );
  19226. const boneInverse = boneInverses[ i ];
  19227. data.boneInverses.push( boneInverse.toArray() );
  19228. }
  19229. return data;
  19230. }
  19231. }
  19232. /**
  19233. * An instanced version of a buffer attribute.
  19234. *
  19235. * @augments BufferAttribute
  19236. */
  19237. class InstancedBufferAttribute extends BufferAttribute {
  19238. /**
  19239. * Constructs a new instanced buffer attribute.
  19240. *
  19241. * @param {TypedArray} array - The array holding the attribute data.
  19242. * @param {number} itemSize - The item size.
  19243. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  19244. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  19245. */
  19246. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19247. super( array, itemSize, normalized );
  19248. /**
  19249. * This flag can be used for type testing.
  19250. *
  19251. * @type {boolean}
  19252. * @readonly
  19253. * @default true
  19254. */
  19255. this.isInstancedBufferAttribute = true;
  19256. /**
  19257. * Defines how often a value of this buffer attribute should be repeated. A
  19258. * value of one means that each value of the instanced attribute is used for
  19259. * a single instance. A value of two means that each value is used for two
  19260. * consecutive instances (and so on).
  19261. *
  19262. * @type {number}
  19263. * @default 1
  19264. */
  19265. this.meshPerAttribute = meshPerAttribute;
  19266. }
  19267. copy( source ) {
  19268. super.copy( source );
  19269. this.meshPerAttribute = source.meshPerAttribute;
  19270. return this;
  19271. }
  19272. toJSON() {
  19273. const data = super.toJSON();
  19274. data.meshPerAttribute = this.meshPerAttribute;
  19275. data.isInstancedBufferAttribute = true;
  19276. return data;
  19277. }
  19278. }
  19279. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19280. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19281. const _instanceIntersects = [];
  19282. const _box3 = /*@__PURE__*/ new Box3();
  19283. const _identity = /*@__PURE__*/ new Matrix4();
  19284. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19285. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19286. /**
  19287. * A special version of a mesh with instanced rendering support. Use
  19288. * this class if you have to render a large number of objects with the same
  19289. * geometry and material(s) but with different world transformations. The usage
  19290. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  19291. * improve the overall rendering performance in your application.
  19292. *
  19293. * @augments Mesh
  19294. */
  19295. class InstancedMesh extends Mesh {
  19296. /**
  19297. * Constructs a new instanced mesh.
  19298. *
  19299. * @param {BufferGeometry} [geometry] - The mesh geometry.
  19300. * @param {Material|Array<Material>} [material] - The mesh material.
  19301. * @param {number} count - The number of instances.
  19302. */
  19303. constructor( geometry, material, count ) {
  19304. super( geometry, material );
  19305. /**
  19306. * This flag can be used for type testing.
  19307. *
  19308. * @type {boolean}
  19309. * @readonly
  19310. * @default true
  19311. */
  19312. this.isInstancedMesh = true;
  19313. /**
  19314. * Represents the local transformation of all instances. You have to set its
  19315. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19316. * via {@link InstancedMesh#setMatrixAt}.
  19317. *
  19318. * @type {InstancedBufferAttribute}
  19319. */
  19320. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19321. /**
  19322. * Represents the local transformation of all instances of the previous frame.
  19323. * Required for computing velocity. Maintained in {@link InstanceNode}.
  19324. *
  19325. * @type {?InstancedBufferAttribute}
  19326. * @default null
  19327. */
  19328. this.previousInstanceMatrix = null;
  19329. /**
  19330. * Represents the color of all instances. You have to set its
  19331. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19332. * via {@link InstancedMesh#setColorAt}.
  19333. *
  19334. * @type {?InstancedBufferAttribute}
  19335. * @default null
  19336. */
  19337. this.instanceColor = null;
  19338. /**
  19339. * Represents the morph target weights of all instances. You have to set its
  19340. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  19341. * via {@link InstancedMesh#setMorphAt}.
  19342. *
  19343. * @type {?DataTexture}
  19344. * @default null
  19345. */
  19346. this.morphTexture = null;
  19347. /**
  19348. * The number of instances.
  19349. *
  19350. * @type {number}
  19351. */
  19352. this.count = count;
  19353. /**
  19354. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  19355. *
  19356. * @type {?Box3}
  19357. * @default null
  19358. */
  19359. this.boundingBox = null;
  19360. /**
  19361. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19362. *
  19363. * @type {?Sphere}
  19364. * @default null
  19365. */
  19366. this.boundingSphere = null;
  19367. for ( let i = 0; i < count; i ++ ) {
  19368. this.setMatrixAt( i, _identity );
  19369. }
  19370. }
  19371. /**
  19372. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19373. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19374. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19375. */
  19376. computeBoundingBox() {
  19377. const geometry = this.geometry;
  19378. const count = this.count;
  19379. if ( this.boundingBox === null ) {
  19380. this.boundingBox = new Box3();
  19381. }
  19382. if ( geometry.boundingBox === null ) {
  19383. geometry.computeBoundingBox();
  19384. }
  19385. this.boundingBox.makeEmpty();
  19386. for ( let i = 0; i < count; i ++ ) {
  19387. this.getMatrixAt( i, _instanceLocalMatrix );
  19388. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19389. this.boundingBox.union( _box3 );
  19390. }
  19391. }
  19392. /**
  19393. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19394. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19395. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19396. */
  19397. computeBoundingSphere() {
  19398. const geometry = this.geometry;
  19399. const count = this.count;
  19400. if ( this.boundingSphere === null ) {
  19401. this.boundingSphere = new Sphere();
  19402. }
  19403. if ( geometry.boundingSphere === null ) {
  19404. geometry.computeBoundingSphere();
  19405. }
  19406. this.boundingSphere.makeEmpty();
  19407. for ( let i = 0; i < count; i ++ ) {
  19408. this.getMatrixAt( i, _instanceLocalMatrix );
  19409. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19410. this.boundingSphere.union( _sphere$4 );
  19411. }
  19412. }
  19413. copy( source, recursive ) {
  19414. super.copy( source, recursive );
  19415. this.instanceMatrix.copy( source.instanceMatrix );
  19416. if ( source.previousInstanceMatrix !== null ) this.previousInstanceMatrix = source.previousInstanceMatrix.clone();
  19417. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19418. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19419. this.count = source.count;
  19420. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19421. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19422. return this;
  19423. }
  19424. /**
  19425. * Gets the color of the defined instance.
  19426. *
  19427. * @param {number} index - The instance index.
  19428. * @param {Color} color - The target object that is used to store the method's result.
  19429. */
  19430. getColorAt( index, color ) {
  19431. color.fromArray( this.instanceColor.array, index * 3 );
  19432. }
  19433. /**
  19434. * Gets the local transformation matrix of the defined instance.
  19435. *
  19436. * @param {number} index - The instance index.
  19437. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19438. */
  19439. getMatrixAt( index, matrix ) {
  19440. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19441. }
  19442. /**
  19443. * Gets the morph target weights of the defined instance.
  19444. *
  19445. * @param {number} index - The instance index.
  19446. * @param {Mesh} object - The target object that is used to store the method's result.
  19447. */
  19448. getMorphAt( index, object ) {
  19449. const objectInfluences = object.morphTargetInfluences;
  19450. const array = this.morphTexture.source.data.data;
  19451. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19452. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19453. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19454. objectInfluences[ i ] = array[ dataIndex + i ];
  19455. }
  19456. }
  19457. raycast( raycaster, intersects ) {
  19458. const matrixWorld = this.matrixWorld;
  19459. const raycastTimes = this.count;
  19460. _mesh$1.geometry = this.geometry;
  19461. _mesh$1.material = this.material;
  19462. if ( _mesh$1.material === undefined ) return;
  19463. // test with bounding sphere first
  19464. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19465. _sphere$4.copy( this.boundingSphere );
  19466. _sphere$4.applyMatrix4( matrixWorld );
  19467. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19468. // now test each instance
  19469. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19470. // calculate the world matrix for each instance
  19471. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19472. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19473. // the mesh represents this single instance
  19474. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19475. _mesh$1.raycast( raycaster, _instanceIntersects );
  19476. // process the result of raycast
  19477. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19478. const intersect = _instanceIntersects[ i ];
  19479. intersect.instanceId = instanceId;
  19480. intersect.object = this;
  19481. intersects.push( intersect );
  19482. }
  19483. _instanceIntersects.length = 0;
  19484. }
  19485. }
  19486. /**
  19487. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19488. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19489. *
  19490. * @param {number} index - The instance index.
  19491. * @param {Color} color - The instance color.
  19492. */
  19493. setColorAt( index, color ) {
  19494. if ( this.instanceColor === null ) {
  19495. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19496. }
  19497. color.toArray( this.instanceColor.array, index * 3 );
  19498. }
  19499. /**
  19500. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19501. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19502. *
  19503. * @param {number} index - The instance index.
  19504. * @param {Matrix4} matrix - The local transformation.
  19505. */
  19506. setMatrixAt( index, matrix ) {
  19507. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19508. }
  19509. /**
  19510. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19511. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19512. *
  19513. * @param {number} index - The instance index.
  19514. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19515. * of a single instance.
  19516. */
  19517. setMorphAt( index, object ) {
  19518. const objectInfluences = object.morphTargetInfluences;
  19519. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19520. if ( this.morphTexture === null ) {
  19521. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19522. }
  19523. const array = this.morphTexture.source.data.data;
  19524. let morphInfluencesSum = 0;
  19525. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19526. morphInfluencesSum += objectInfluences[ i ];
  19527. }
  19528. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19529. const dataIndex = len * index;
  19530. array[ dataIndex ] = morphBaseInfluence;
  19531. array.set( objectInfluences, dataIndex + 1 );
  19532. }
  19533. updateMorphTargets() {
  19534. }
  19535. /**
  19536. * Frees the GPU-related resources allocated by this instance. Call this
  19537. * method whenever this instance is no longer used in your app.
  19538. */
  19539. dispose() {
  19540. this.dispatchEvent( { type: 'dispose' } );
  19541. if ( this.morphTexture !== null ) {
  19542. this.morphTexture.dispose();
  19543. this.morphTexture = null;
  19544. }
  19545. }
  19546. }
  19547. const _vector1 = /*@__PURE__*/ new Vector3();
  19548. const _vector2 = /*@__PURE__*/ new Vector3();
  19549. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19550. /**
  19551. * A two dimensional surface that extends infinitely in 3D space, represented
  19552. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  19553. * by a unit length normal vector and a constant.
  19554. */
  19555. class Plane {
  19556. /**
  19557. * Constructs a new plane.
  19558. *
  19559. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19560. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19561. */
  19562. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19563. /**
  19564. * This flag can be used for type testing.
  19565. *
  19566. * @type {boolean}
  19567. * @readonly
  19568. * @default true
  19569. */
  19570. this.isPlane = true;
  19571. /**
  19572. * A unit length vector defining the normal of the plane.
  19573. *
  19574. * @type {Vector3}
  19575. */
  19576. this.normal = normal;
  19577. /**
  19578. * The signed distance from the origin to the plane.
  19579. *
  19580. * @type {number}
  19581. * @default 0
  19582. */
  19583. this.constant = constant;
  19584. }
  19585. /**
  19586. * Sets the plane components by copying the given values.
  19587. *
  19588. * @param {Vector3} normal - The normal.
  19589. * @param {number} constant - The constant.
  19590. * @return {Plane} A reference to this plane.
  19591. */
  19592. set( normal, constant ) {
  19593. this.normal.copy( normal );
  19594. this.constant = constant;
  19595. return this;
  19596. }
  19597. /**
  19598. * Sets the plane components by defining `x`, `y`, `z` as the
  19599. * plane normal and `w` as the constant.
  19600. *
  19601. * @param {number} x - The value for the normal's x component.
  19602. * @param {number} y - The value for the normal's y component.
  19603. * @param {number} z - The value for the normal's z component.
  19604. * @param {number} w - The constant value.
  19605. * @return {Plane} A reference to this plane.
  19606. */
  19607. setComponents( x, y, z, w ) {
  19608. this.normal.set( x, y, z );
  19609. this.constant = w;
  19610. return this;
  19611. }
  19612. /**
  19613. * Sets the plane from the given normal and coplanar point (that is a point
  19614. * that lies onto the plane).
  19615. *
  19616. * @param {Vector3} normal - The normal.
  19617. * @param {Vector3} point - A coplanar point.
  19618. * @return {Plane} A reference to this plane.
  19619. */
  19620. setFromNormalAndCoplanarPoint( normal, point ) {
  19621. this.normal.copy( normal );
  19622. this.constant = - point.dot( this.normal );
  19623. return this;
  19624. }
  19625. /**
  19626. * Sets the plane from three coplanar points. The winding order is
  19627. * assumed to be counter-clockwise, and determines the direction of
  19628. * the plane normal.
  19629. *
  19630. * @param {Vector3} a - The first coplanar point.
  19631. * @param {Vector3} b - The second coplanar point.
  19632. * @param {Vector3} c - The third coplanar point.
  19633. * @return {Plane} A reference to this plane.
  19634. */
  19635. setFromCoplanarPoints( a, b, c ) {
  19636. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19637. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19638. this.setFromNormalAndCoplanarPoint( normal, a );
  19639. return this;
  19640. }
  19641. /**
  19642. * Copies the values of the given plane to this instance.
  19643. *
  19644. * @param {Plane} plane - The plane to copy.
  19645. * @return {Plane} A reference to this plane.
  19646. */
  19647. copy( plane ) {
  19648. this.normal.copy( plane.normal );
  19649. this.constant = plane.constant;
  19650. return this;
  19651. }
  19652. /**
  19653. * Normalizes the plane normal and adjusts the constant accordingly.
  19654. *
  19655. * @return {Plane} A reference to this plane.
  19656. */
  19657. normalize() {
  19658. // Note: will lead to a divide by zero if the plane is invalid.
  19659. const inverseNormalLength = 1.0 / this.normal.length();
  19660. this.normal.multiplyScalar( inverseNormalLength );
  19661. this.constant *= inverseNormalLength;
  19662. return this;
  19663. }
  19664. /**
  19665. * Negates both the plane normal and the constant.
  19666. *
  19667. * @return {Plane} A reference to this plane.
  19668. */
  19669. negate() {
  19670. this.constant *= -1;
  19671. this.normal.negate();
  19672. return this;
  19673. }
  19674. /**
  19675. * Returns the signed distance from the given point to this plane.
  19676. *
  19677. * @param {Vector3} point - The point to compute the distance for.
  19678. * @return {number} The signed distance.
  19679. */
  19680. distanceToPoint( point ) {
  19681. return this.normal.dot( point ) + this.constant;
  19682. }
  19683. /**
  19684. * Returns the signed distance from the given sphere to this plane.
  19685. *
  19686. * @param {Sphere} sphere - The sphere to compute the distance for.
  19687. * @return {number} The signed distance.
  19688. */
  19689. distanceToSphere( sphere ) {
  19690. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19691. }
  19692. /**
  19693. * Projects a the given point onto the plane.
  19694. *
  19695. * @param {Vector3} point - The point to project.
  19696. * @param {Vector3} target - The target vector that is used to store the method's result.
  19697. * @return {Vector3} The projected point on the plane.
  19698. */
  19699. projectPoint( point, target ) {
  19700. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19701. }
  19702. /**
  19703. * Returns the intersection point of the passed line and the plane. Returns
  19704. * `null` if the line does not intersect. Returns the line's starting point if
  19705. * the line is coplanar with the plane.
  19706. *
  19707. * @param {Line3} line - The line to compute the intersection for.
  19708. * @param {Vector3} target - The target vector that is used to store the method's result.
  19709. * @return {?Vector3} The intersection point.
  19710. */
  19711. intersectLine( line, target ) {
  19712. const direction = line.delta( _vector1 );
  19713. const denominator = this.normal.dot( direction );
  19714. if ( denominator === 0 ) {
  19715. // line is coplanar, return origin
  19716. if ( this.distanceToPoint( line.start ) === 0 ) {
  19717. return target.copy( line.start );
  19718. }
  19719. // Unsure if this is the correct method to handle this case.
  19720. return null;
  19721. }
  19722. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19723. if ( t < 0 || t > 1 ) {
  19724. return null;
  19725. }
  19726. return target.copy( line.start ).addScaledVector( direction, t );
  19727. }
  19728. /**
  19729. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19730. *
  19731. * @param {Line3} line - The line to test.
  19732. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19733. */
  19734. intersectsLine( line ) {
  19735. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19736. const startSign = this.distanceToPoint( line.start );
  19737. const endSign = this.distanceToPoint( line.end );
  19738. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19739. }
  19740. /**
  19741. * Returns `true` if the given bounding box intersects with the plane.
  19742. *
  19743. * @param {Box3} box - The bounding box to test.
  19744. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19745. */
  19746. intersectsBox( box ) {
  19747. return box.intersectsPlane( this );
  19748. }
  19749. /**
  19750. * Returns `true` if the given bounding sphere intersects with the plane.
  19751. *
  19752. * @param {Sphere} sphere - The bounding sphere to test.
  19753. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19754. */
  19755. intersectsSphere( sphere ) {
  19756. return sphere.intersectsPlane( this );
  19757. }
  19758. /**
  19759. * Returns a coplanar vector to the plane, by calculating the
  19760. * projection of the normal at the origin onto the plane.
  19761. *
  19762. * @param {Vector3} target - The target vector that is used to store the method's result.
  19763. * @return {Vector3} The coplanar point.
  19764. */
  19765. coplanarPoint( target ) {
  19766. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19767. }
  19768. /**
  19769. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19770. *
  19771. * The optional normal matrix can be pre-computed like so:
  19772. * ```js
  19773. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19774. * ```
  19775. *
  19776. * @param {Matrix4} matrix - The transformation matrix.
  19777. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19778. * @return {Plane} A reference to this plane.
  19779. */
  19780. applyMatrix4( matrix, optionalNormalMatrix ) {
  19781. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19782. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19783. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19784. this.constant = - referencePoint.dot( normal );
  19785. return this;
  19786. }
  19787. /**
  19788. * Translates the plane by the distance defined by the given offset vector.
  19789. * Note that this only affects the plane constant and will not affect the normal vector.
  19790. *
  19791. * @param {Vector3} offset - The offset vector.
  19792. * @return {Plane} A reference to this plane.
  19793. */
  19794. translate( offset ) {
  19795. this.constant -= offset.dot( this.normal );
  19796. return this;
  19797. }
  19798. /**
  19799. * Returns `true` if this plane is equal with the given one.
  19800. *
  19801. * @param {Plane} plane - The plane to test for equality.
  19802. * @return {boolean} Whether this plane is equal with the given one.
  19803. */
  19804. equals( plane ) {
  19805. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19806. }
  19807. /**
  19808. * Returns a new plane with copied values from this instance.
  19809. *
  19810. * @return {Plane} A clone of this instance.
  19811. */
  19812. clone() {
  19813. return new this.constructor().copy( this );
  19814. }
  19815. }
  19816. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19817. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19818. const _vector$6 = /*@__PURE__*/ new Vector3();
  19819. /**
  19820. * Frustums are used to determine what is inside the camera's field of view.
  19821. * They help speed up the rendering process - objects which lie outside a camera's
  19822. * frustum can safely be excluded from rendering.
  19823. *
  19824. * This class is mainly intended for use internally by a renderer.
  19825. */
  19826. class Frustum {
  19827. /**
  19828. * Constructs a new frustum.
  19829. *
  19830. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19831. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19832. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19833. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19834. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19835. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19836. */
  19837. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19838. /**
  19839. * This array holds the planes that enclose the frustum.
  19840. *
  19841. * @type {Array<Plane>}
  19842. */
  19843. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19844. }
  19845. /**
  19846. * Sets the frustum planes by copying the given planes.
  19847. *
  19848. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19849. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19850. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19851. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19852. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19853. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19854. * @return {Frustum} A reference to this frustum.
  19855. */
  19856. set( p0, p1, p2, p3, p4, p5 ) {
  19857. const planes = this.planes;
  19858. planes[ 0 ].copy( p0 );
  19859. planes[ 1 ].copy( p1 );
  19860. planes[ 2 ].copy( p2 );
  19861. planes[ 3 ].copy( p3 );
  19862. planes[ 4 ].copy( p4 );
  19863. planes[ 5 ].copy( p5 );
  19864. return this;
  19865. }
  19866. /**
  19867. * Copies the values of the given frustum to this instance.
  19868. *
  19869. * @param {Frustum} frustum - The frustum to copy.
  19870. * @return {Frustum} A reference to this frustum.
  19871. */
  19872. copy( frustum ) {
  19873. const planes = this.planes;
  19874. for ( let i = 0; i < 6; i ++ ) {
  19875. planes[ i ].copy( frustum.planes[ i ] );
  19876. }
  19877. return this;
  19878. }
  19879. /**
  19880. * Sets the frustum planes from the given projection matrix.
  19881. *
  19882. * @param {Matrix4} m - The projection matrix.
  19883. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19884. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19885. * @return {Frustum} A reference to this frustum.
  19886. */
  19887. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19888. const planes = this.planes;
  19889. const me = m.elements;
  19890. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19891. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19892. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19893. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19894. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19895. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19896. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19897. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19898. if ( reversedDepth ) {
  19899. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19900. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19901. } else {
  19902. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19903. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19904. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19905. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19906. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19907. } else {
  19908. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19909. }
  19910. }
  19911. return this;
  19912. }
  19913. /**
  19914. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19915. *
  19916. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19917. *
  19918. * @param {Object3D} object - The 3D object to test.
  19919. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19920. */
  19921. intersectsObject( object ) {
  19922. if ( object.boundingSphere !== undefined ) {
  19923. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19924. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19925. } else {
  19926. const geometry = object.geometry;
  19927. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19928. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19929. }
  19930. return this.intersectsSphere( _sphere$3 );
  19931. }
  19932. /**
  19933. * Returns `true` if the given sprite is intersecting this frustum.
  19934. *
  19935. * @param {Sprite} sprite - The sprite to test.
  19936. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19937. */
  19938. intersectsSprite( sprite ) {
  19939. _sphere$3.center.set( 0, 0, 0 );
  19940. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19941. _sphere$3.radius = 0.7071067811865476 + offset;
  19942. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19943. return this.intersectsSphere( _sphere$3 );
  19944. }
  19945. /**
  19946. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19947. *
  19948. * @param {Sphere} sphere - The bounding sphere to test.
  19949. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19950. */
  19951. intersectsSphere( sphere ) {
  19952. const planes = this.planes;
  19953. const center = sphere.center;
  19954. const negRadius = - sphere.radius;
  19955. for ( let i = 0; i < 6; i ++ ) {
  19956. const distance = planes[ i ].distanceToPoint( center );
  19957. if ( distance < negRadius ) {
  19958. return false;
  19959. }
  19960. }
  19961. return true;
  19962. }
  19963. /**
  19964. * Returns `true` if the given bounding box is intersecting this frustum.
  19965. *
  19966. * @param {Box3} box - The bounding box to test.
  19967. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19968. */
  19969. intersectsBox( box ) {
  19970. const planes = this.planes;
  19971. for ( let i = 0; i < 6; i ++ ) {
  19972. const plane = planes[ i ];
  19973. // corner at max distance
  19974. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19975. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19976. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19977. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19978. return false;
  19979. }
  19980. }
  19981. return true;
  19982. }
  19983. /**
  19984. * Returns `true` if the given point lies within the frustum.
  19985. *
  19986. * @param {Vector3} point - The point to test.
  19987. * @return {boolean} Whether the point lies within this frustum or not.
  19988. */
  19989. containsPoint( point ) {
  19990. const planes = this.planes;
  19991. for ( let i = 0; i < 6; i ++ ) {
  19992. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19993. return false;
  19994. }
  19995. }
  19996. return true;
  19997. }
  19998. /**
  19999. * Returns a new frustum with copied values from this instance.
  20000. *
  20001. * @return {Frustum} A clone of this instance.
  20002. */
  20003. clone() {
  20004. return new this.constructor().copy( this );
  20005. }
  20006. }
  20007. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  20008. const _frustum$1 = /*@__PURE__*/ new Frustum();
  20009. /**
  20010. * FrustumArray is used to determine if an object is visible in at least one camera
  20011. * from an array of cameras. This is particularly useful for multi-view renderers.
  20012. */
  20013. class FrustumArray {
  20014. /**
  20015. * Constructs a new frustum array.
  20016. *
  20017. */
  20018. constructor() {
  20019. /**
  20020. * The coordinate system to use.
  20021. *
  20022. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  20023. * @default WebGLCoordinateSystem
  20024. */
  20025. this.coordinateSystem = WebGLCoordinateSystem;
  20026. }
  20027. /**
  20028. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  20029. * from the camera array.
  20030. *
  20031. * @param {Object3D} object - The 3D object to test.
  20032. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20033. * @return {boolean} Whether the 3D object is visible in any camera.
  20034. */
  20035. intersectsObject( object, cameraArray ) {
  20036. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  20037. return false;
  20038. }
  20039. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20040. const camera = cameraArray.cameras[ i ];
  20041. _projScreenMatrix$1.multiplyMatrices(
  20042. camera.projectionMatrix,
  20043. camera.matrixWorldInverse
  20044. );
  20045. _frustum$1.setFromProjectionMatrix(
  20046. _projScreenMatrix$1,
  20047. camera.coordinateSystem,
  20048. camera.reversedDepth
  20049. );
  20050. if ( _frustum$1.intersectsObject( object ) ) {
  20051. return true; // Object is visible in at least one camera
  20052. }
  20053. }
  20054. return false; // Not visible in any camera
  20055. }
  20056. /**
  20057. * Returns `true` if the given sprite is intersecting any frustum
  20058. * from the camera array.
  20059. *
  20060. * @param {Sprite} sprite - The sprite to test.
  20061. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20062. * @return {boolean} Whether the sprite is visible in any camera.
  20063. */
  20064. intersectsSprite( sprite, cameraArray ) {
  20065. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20066. return false;
  20067. }
  20068. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20069. const camera = cameraArray.cameras[ i ];
  20070. _projScreenMatrix$1.multiplyMatrices(
  20071. camera.projectionMatrix,
  20072. camera.matrixWorldInverse
  20073. );
  20074. _frustum$1.setFromProjectionMatrix(
  20075. _projScreenMatrix$1,
  20076. camera.coordinateSystem,
  20077. camera.reversedDepth
  20078. );
  20079. if ( _frustum$1.intersectsSprite( sprite ) ) {
  20080. return true; // Sprite is visible in at least one camera
  20081. }
  20082. }
  20083. return false; // Not visible in any camera
  20084. }
  20085. /**
  20086. * Returns `true` if the given bounding sphere is intersecting any frustum
  20087. * from the camera array.
  20088. *
  20089. * @param {Sphere} sphere - The bounding sphere to test.
  20090. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20091. * @return {boolean} Whether the sphere is visible in any camera.
  20092. */
  20093. intersectsSphere( sphere, cameraArray ) {
  20094. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20095. return false;
  20096. }
  20097. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20098. const camera = cameraArray.cameras[ i ];
  20099. _projScreenMatrix$1.multiplyMatrices(
  20100. camera.projectionMatrix,
  20101. camera.matrixWorldInverse
  20102. );
  20103. _frustum$1.setFromProjectionMatrix(
  20104. _projScreenMatrix$1,
  20105. camera.coordinateSystem,
  20106. camera.reversedDepth
  20107. );
  20108. if ( _frustum$1.intersectsSphere( sphere ) ) {
  20109. return true; // Sphere is visible in at least one camera
  20110. }
  20111. }
  20112. return false; // Not visible in any camera
  20113. }
  20114. /**
  20115. * Returns `true` if the given bounding box is intersecting any frustum
  20116. * from the camera array.
  20117. *
  20118. * @param {Box3} box - The bounding box to test.
  20119. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20120. * @return {boolean} Whether the box is visible in any camera.
  20121. */
  20122. intersectsBox( box, cameraArray ) {
  20123. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20124. return false;
  20125. }
  20126. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20127. const camera = cameraArray.cameras[ i ];
  20128. _projScreenMatrix$1.multiplyMatrices(
  20129. camera.projectionMatrix,
  20130. camera.matrixWorldInverse
  20131. );
  20132. _frustum$1.setFromProjectionMatrix(
  20133. _projScreenMatrix$1,
  20134. camera.coordinateSystem,
  20135. camera.reversedDepth
  20136. );
  20137. if ( _frustum$1.intersectsBox( box ) ) {
  20138. return true; // Box is visible in at least one camera
  20139. }
  20140. }
  20141. return false; // Not visible in any camera
  20142. }
  20143. /**
  20144. * Returns `true` if the given point lies within any frustum
  20145. * from the camera array.
  20146. *
  20147. * @param {Vector3} point - The point to test.
  20148. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20149. * @return {boolean} Whether the point is visible in any camera.
  20150. */
  20151. containsPoint( point, cameraArray ) {
  20152. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20153. return false;
  20154. }
  20155. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20156. const camera = cameraArray.cameras[ i ];
  20157. _projScreenMatrix$1.multiplyMatrices(
  20158. camera.projectionMatrix,
  20159. camera.matrixWorldInverse
  20160. );
  20161. _frustum$1.setFromProjectionMatrix(
  20162. _projScreenMatrix$1,
  20163. camera.coordinateSystem,
  20164. camera.reversedDepth
  20165. );
  20166. if ( _frustum$1.containsPoint( point ) ) {
  20167. return true; // Point is visible in at least one camera
  20168. }
  20169. }
  20170. return false; // Not visible in any camera
  20171. }
  20172. /**
  20173. * Returns a new frustum array with copied values from this instance.
  20174. *
  20175. * @return {FrustumArray} A clone of this instance.
  20176. */
  20177. clone() {
  20178. return new FrustumArray();
  20179. }
  20180. }
  20181. function ascIdSort( a, b ) {
  20182. return a - b;
  20183. }
  20184. function sortOpaque( a, b ) {
  20185. return a.z - b.z;
  20186. }
  20187. function sortTransparent( a, b ) {
  20188. return b.z - a.z;
  20189. }
  20190. class MultiDrawRenderList {
  20191. constructor() {
  20192. this.index = 0;
  20193. this.pool = [];
  20194. this.list = [];
  20195. }
  20196. push( start, count, z, index ) {
  20197. const pool = this.pool;
  20198. const list = this.list;
  20199. if ( this.index >= pool.length ) {
  20200. pool.push( {
  20201. start: -1,
  20202. count: -1,
  20203. z: -1,
  20204. index: -1,
  20205. } );
  20206. }
  20207. const item = pool[ this.index ];
  20208. list.push( item );
  20209. this.index ++;
  20210. item.start = start;
  20211. item.count = count;
  20212. item.z = z;
  20213. item.index = index;
  20214. }
  20215. reset() {
  20216. this.list.length = 0;
  20217. this.index = 0;
  20218. }
  20219. }
  20220. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  20221. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  20222. const _frustum = /*@__PURE__*/ new Frustum();
  20223. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  20224. const _box$1 = /*@__PURE__*/ new Box3();
  20225. const _sphere$2 = /*@__PURE__*/ new Sphere();
  20226. const _vector$5 = /*@__PURE__*/ new Vector3();
  20227. const _forward$1 = /*@__PURE__*/ new Vector3();
  20228. const _temp = /*@__PURE__*/ new Vector3();
  20229. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  20230. const _mesh = /*@__PURE__*/ new Mesh();
  20231. const _batchIntersects = [];
  20232. // copies data from attribute "src" into "target" starting at "targetOffset"
  20233. function copyAttributeData( src, target, targetOffset = 0 ) {
  20234. const itemSize = target.itemSize;
  20235. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  20236. // use the component getters and setters if the array data cannot
  20237. // be copied directly
  20238. const vertexCount = src.count;
  20239. for ( let i = 0; i < vertexCount; i ++ ) {
  20240. for ( let c = 0; c < itemSize; c ++ ) {
  20241. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  20242. }
  20243. }
  20244. } else {
  20245. // faster copy approach using typed array set function
  20246. target.array.set( src.array, targetOffset * itemSize );
  20247. }
  20248. target.needsUpdate = true;
  20249. }
  20250. // safely copies array contents to a potentially smaller array
  20251. function copyArrayContents( src, target ) {
  20252. if ( src.constructor !== target.constructor ) {
  20253. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  20254. const len = Math.min( src.length, target.length );
  20255. for ( let i = 0; i < len; i ++ ) {
  20256. target[ i ] = src[ i ];
  20257. }
  20258. } else {
  20259. // if the arrays use the same data layout we can use a fast block copy
  20260. const len = Math.min( src.length, target.length );
  20261. target.set( new src.constructor( src.buffer, 0, len ) );
  20262. }
  20263. }
  20264. /**
  20265. * A special version of a mesh with multi draw batch rendering support. Use
  20266. * this class if you have to render a large number of objects with the same
  20267. * material but with different geometries or world transformations. The usage of
  20268. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  20269. * rendering performance in your application.
  20270. *
  20271. * ```js
  20272. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  20273. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  20274. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  20275. *
  20276. * // initialize and add geometries into the batched mesh
  20277. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  20278. * const boxGeometryId = batchedMesh.addGeometry( box );
  20279. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  20280. *
  20281. * // create instances of those geometries
  20282. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  20283. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  20284. *
  20285. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  20286. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  20287. *
  20288. * // position the geometries
  20289. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  20290. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  20291. *
  20292. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  20293. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  20294. *
  20295. * scene.add( batchedMesh );
  20296. * ```
  20297. *
  20298. * @augments Mesh
  20299. */
  20300. class BatchedMesh extends Mesh {
  20301. /**
  20302. * Constructs a new batched mesh.
  20303. *
  20304. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  20305. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  20306. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  20307. * @param {Material|Array<Material>} [material] - The mesh material.
  20308. */
  20309. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  20310. super( new BufferGeometry(), material );
  20311. /**
  20312. * This flag can be used for type testing.
  20313. *
  20314. * @type {boolean}
  20315. * @readonly
  20316. * @default true
  20317. */
  20318. this.isBatchedMesh = true;
  20319. /**
  20320. * When set ot `true`, the individual objects of a batch are frustum culled.
  20321. *
  20322. * @type {boolean}
  20323. * @default true
  20324. */
  20325. this.perObjectFrustumCulled = true;
  20326. /**
  20327. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  20328. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  20329. * rendered front to back.
  20330. *
  20331. * @type {boolean}
  20332. * @default true
  20333. */
  20334. this.sortObjects = true;
  20335. /**
  20336. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  20337. *
  20338. * @type {?Box3}
  20339. * @default null
  20340. */
  20341. this.boundingBox = null;
  20342. /**
  20343. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  20344. *
  20345. * @type {?Sphere}
  20346. * @default null
  20347. */
  20348. this.boundingSphere = null;
  20349. /**
  20350. * Takes a sort a function that is run before render. The function takes a list of instances to
  20351. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  20352. * sort with.
  20353. *
  20354. * @type {?Function}
  20355. * @default null
  20356. */
  20357. this.customSort = null;
  20358. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20359. this._instanceInfo = [];
  20360. this._geometryInfo = [];
  20361. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20362. this._availableInstanceIds = [];
  20363. this._availableGeometryIds = [];
  20364. // used to track where the next point is that geometry should be inserted
  20365. this._nextIndexStart = 0;
  20366. this._nextVertexStart = 0;
  20367. this._geometryCount = 0;
  20368. // flags
  20369. this._visibilityChanged = true;
  20370. this._geometryInitialized = false;
  20371. // cached user options
  20372. this._maxInstanceCount = maxInstanceCount;
  20373. this._maxVertexCount = maxVertexCount;
  20374. this._maxIndexCount = maxIndexCount;
  20375. // buffers for multi draw
  20376. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20377. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20378. this._multiDrawCount = 0;
  20379. this._multiDrawInstances = null;
  20380. // Local matrix per geometry by using data texture
  20381. this._matricesTexture = null;
  20382. this._indirectTexture = null;
  20383. this._colorsTexture = null;
  20384. this._initMatricesTexture();
  20385. this._initIndirectTexture();
  20386. }
  20387. /**
  20388. * The maximum number of individual instances that can be stored in the batch.
  20389. *
  20390. * @type {number}
  20391. * @readonly
  20392. */
  20393. get maxInstanceCount() {
  20394. return this._maxInstanceCount;
  20395. }
  20396. /**
  20397. * The instance count.
  20398. *
  20399. * @type {number}
  20400. * @readonly
  20401. */
  20402. get instanceCount() {
  20403. return this._instanceInfo.length - this._availableInstanceIds.length;
  20404. }
  20405. /**
  20406. * The number of unused vertices.
  20407. *
  20408. * @type {number}
  20409. * @readonly
  20410. */
  20411. get unusedVertexCount() {
  20412. return this._maxVertexCount - this._nextVertexStart;
  20413. }
  20414. /**
  20415. * The number of unused indices.
  20416. *
  20417. * @type {number}
  20418. * @readonly
  20419. */
  20420. get unusedIndexCount() {
  20421. return this._maxIndexCount - this._nextIndexStart;
  20422. }
  20423. _initMatricesTexture() {
  20424. // layout (1 matrix = 4 pixels)
  20425. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20426. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20427. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20428. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20429. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20430. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20431. size = Math.ceil( size / 4 ) * 4;
  20432. size = Math.max( size, 4 );
  20433. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20434. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20435. this._matricesTexture = matricesTexture;
  20436. }
  20437. _initIndirectTexture() {
  20438. let size = Math.sqrt( this._maxInstanceCount );
  20439. size = Math.ceil( size );
  20440. const indirectArray = new Uint32Array( size * size );
  20441. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20442. this._indirectTexture = indirectTexture;
  20443. }
  20444. _initColorsTexture() {
  20445. let size = Math.sqrt( this._maxInstanceCount );
  20446. size = Math.ceil( size );
  20447. // 4 floats per RGBA pixel initialized to white
  20448. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20449. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20450. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20451. this._colorsTexture = colorsTexture;
  20452. }
  20453. _initializeGeometry( reference ) {
  20454. const geometry = this.geometry;
  20455. const maxVertexCount = this._maxVertexCount;
  20456. const maxIndexCount = this._maxIndexCount;
  20457. if ( this._geometryInitialized === false ) {
  20458. for ( const attributeName in reference.attributes ) {
  20459. const srcAttribute = reference.getAttribute( attributeName );
  20460. const { array, itemSize, normalized } = srcAttribute;
  20461. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20462. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20463. geometry.setAttribute( attributeName, dstAttribute );
  20464. }
  20465. if ( reference.getIndex() !== null ) {
  20466. // Reserve last u16 index for primitive restart.
  20467. const indexArray = maxVertexCount > 65535
  20468. ? new Uint32Array( maxIndexCount )
  20469. : new Uint16Array( maxIndexCount );
  20470. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20471. }
  20472. this._geometryInitialized = true;
  20473. }
  20474. }
  20475. // Make sure the geometry is compatible with the existing combined geometry attributes
  20476. _validateGeometry( geometry ) {
  20477. // check to ensure the geometries are using consistent attributes and indices
  20478. const batchGeometry = this.geometry;
  20479. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20480. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20481. }
  20482. for ( const attributeName in batchGeometry.attributes ) {
  20483. if ( ! geometry.hasAttribute( attributeName ) ) {
  20484. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20485. }
  20486. const srcAttribute = geometry.getAttribute( attributeName );
  20487. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20488. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20489. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20490. }
  20491. }
  20492. }
  20493. /**
  20494. * Validates the instance defined by the given ID.
  20495. *
  20496. * @param {number} instanceId - The instance to validate.
  20497. */
  20498. validateInstanceId( instanceId ) {
  20499. const instanceInfo = this._instanceInfo;
  20500. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20501. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20502. }
  20503. }
  20504. /**
  20505. * Validates the geometry defined by the given ID.
  20506. *
  20507. * @param {number} geometryId - The geometry to validate.
  20508. */
  20509. validateGeometryId( geometryId ) {
  20510. const geometryInfoList = this._geometryInfo;
  20511. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20512. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20513. }
  20514. }
  20515. /**
  20516. * Takes a sort a function that is run before render. The function takes a list of instances to
  20517. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20518. *
  20519. * @param {Function} func - The custom sort function.
  20520. * @return {BatchedMesh} A reference to this batched mesh.
  20521. */
  20522. setCustomSort( func ) {
  20523. this.customSort = func;
  20524. return this;
  20525. }
  20526. /**
  20527. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20528. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20529. * otherwise they are `null`.
  20530. */
  20531. computeBoundingBox() {
  20532. if ( this.boundingBox === null ) {
  20533. this.boundingBox = new Box3();
  20534. }
  20535. const boundingBox = this.boundingBox;
  20536. const instanceInfo = this._instanceInfo;
  20537. boundingBox.makeEmpty();
  20538. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20539. if ( instanceInfo[ i ].active === false ) continue;
  20540. const geometryId = instanceInfo[ i ].geometryIndex;
  20541. this.getMatrixAt( i, _matrix$1 );
  20542. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20543. boundingBox.union( _box$1 );
  20544. }
  20545. }
  20546. /**
  20547. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20548. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20549. * otherwise they are `null`.
  20550. */
  20551. computeBoundingSphere() {
  20552. if ( this.boundingSphere === null ) {
  20553. this.boundingSphere = new Sphere();
  20554. }
  20555. const boundingSphere = this.boundingSphere;
  20556. const instanceInfo = this._instanceInfo;
  20557. boundingSphere.makeEmpty();
  20558. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20559. if ( instanceInfo[ i ].active === false ) continue;
  20560. const geometryId = instanceInfo[ i ].geometryIndex;
  20561. this.getMatrixAt( i, _matrix$1 );
  20562. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20563. boundingSphere.union( _sphere$2 );
  20564. }
  20565. }
  20566. /**
  20567. * Adds a new instance to the batch using the geometry of the given ID and returns
  20568. * a new id referring to the new instance to be used by other functions.
  20569. *
  20570. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20571. * @return {number} The instance ID.
  20572. */
  20573. addInstance( geometryId ) {
  20574. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20575. // ensure we're not over geometry
  20576. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20577. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20578. }
  20579. const instanceInfo = {
  20580. visible: true,
  20581. active: true,
  20582. geometryIndex: geometryId,
  20583. };
  20584. let drawId = null;
  20585. // Prioritize using previously freed instance ids
  20586. if ( this._availableInstanceIds.length > 0 ) {
  20587. this._availableInstanceIds.sort( ascIdSort );
  20588. drawId = this._availableInstanceIds.shift();
  20589. this._instanceInfo[ drawId ] = instanceInfo;
  20590. } else {
  20591. drawId = this._instanceInfo.length;
  20592. this._instanceInfo.push( instanceInfo );
  20593. }
  20594. const matricesTexture = this._matricesTexture;
  20595. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20596. matricesTexture.needsUpdate = true;
  20597. const colorsTexture = this._colorsTexture;
  20598. if ( colorsTexture ) {
  20599. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20600. colorsTexture.needsUpdate = true;
  20601. }
  20602. this._visibilityChanged = true;
  20603. return drawId;
  20604. }
  20605. /**
  20606. * Adds the given geometry to the batch and returns the associated
  20607. * geometry id referring to it to be used in other functions.
  20608. *
  20609. * @param {BufferGeometry} geometry - The geometry to add.
  20610. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20611. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20612. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20613. * Defaults to the length of the given geometry vertex buffer.
  20614. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20615. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20616. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20617. * the length of the given geometry index buffer.
  20618. * @return {number} The geometry ID.
  20619. */
  20620. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20621. this._initializeGeometry( geometry );
  20622. this._validateGeometry( geometry );
  20623. const geometryInfo = {
  20624. // geometry information
  20625. vertexStart: -1,
  20626. vertexCount: -1,
  20627. reservedVertexCount: -1,
  20628. indexStart: -1,
  20629. indexCount: -1,
  20630. reservedIndexCount: -1,
  20631. // draw range information
  20632. start: -1,
  20633. count: -1,
  20634. // state
  20635. boundingBox: null,
  20636. boundingSphere: null,
  20637. active: true,
  20638. };
  20639. const geometryInfoList = this._geometryInfo;
  20640. geometryInfo.vertexStart = this._nextVertexStart;
  20641. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20642. const index = geometry.getIndex();
  20643. const hasIndex = index !== null;
  20644. if ( hasIndex ) {
  20645. geometryInfo.indexStart = this._nextIndexStart;
  20646. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20647. }
  20648. if (
  20649. geometryInfo.indexStart !== -1 &&
  20650. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20651. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20652. ) {
  20653. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20654. }
  20655. // update id
  20656. let geometryId;
  20657. if ( this._availableGeometryIds.length > 0 ) {
  20658. this._availableGeometryIds.sort( ascIdSort );
  20659. geometryId = this._availableGeometryIds.shift();
  20660. geometryInfoList[ geometryId ] = geometryInfo;
  20661. } else {
  20662. geometryId = this._geometryCount;
  20663. this._geometryCount ++;
  20664. geometryInfoList.push( geometryInfo );
  20665. }
  20666. // update the geometry
  20667. this.setGeometryAt( geometryId, geometry );
  20668. // increment the next geometry position
  20669. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20670. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20671. return geometryId;
  20672. }
  20673. /**
  20674. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20675. * is not enough space reserved for geometry. Calling this will change all instances that are
  20676. * rendering that geometry.
  20677. *
  20678. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20679. * @param {BufferGeometry} geometry - The new geometry.
  20680. * @return {number} The geometry ID.
  20681. */
  20682. setGeometryAt( geometryId, geometry ) {
  20683. if ( geometryId >= this._geometryCount ) {
  20684. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20685. }
  20686. this._validateGeometry( geometry );
  20687. const batchGeometry = this.geometry;
  20688. const hasIndex = batchGeometry.getIndex() !== null;
  20689. const dstIndex = batchGeometry.getIndex();
  20690. const srcIndex = geometry.getIndex();
  20691. const geometryInfo = this._geometryInfo[ geometryId ];
  20692. if (
  20693. hasIndex &&
  20694. srcIndex.count > geometryInfo.reservedIndexCount ||
  20695. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20696. ) {
  20697. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20698. }
  20699. // copy geometry buffer data over
  20700. const vertexStart = geometryInfo.vertexStart;
  20701. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20702. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20703. for ( const attributeName in batchGeometry.attributes ) {
  20704. // copy attribute data
  20705. const srcAttribute = geometry.getAttribute( attributeName );
  20706. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20707. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20708. // fill the rest in with zeroes
  20709. const itemSize = srcAttribute.itemSize;
  20710. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20711. const index = vertexStart + i;
  20712. for ( let c = 0; c < itemSize; c ++ ) {
  20713. dstAttribute.setComponent( index, c, 0 );
  20714. }
  20715. }
  20716. dstAttribute.needsUpdate = true;
  20717. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20718. }
  20719. // copy index
  20720. if ( hasIndex ) {
  20721. const indexStart = geometryInfo.indexStart;
  20722. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20723. geometryInfo.indexCount = geometry.getIndex().count;
  20724. // copy index data over
  20725. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20726. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20727. }
  20728. // fill the rest in with zeroes
  20729. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20730. dstIndex.setX( indexStart + i, vertexStart );
  20731. }
  20732. dstIndex.needsUpdate = true;
  20733. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20734. }
  20735. // update the draw range
  20736. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20737. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20738. // store the bounding boxes
  20739. geometryInfo.boundingBox = null;
  20740. if ( geometry.boundingBox !== null ) {
  20741. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20742. }
  20743. geometryInfo.boundingSphere = null;
  20744. if ( geometry.boundingSphere !== null ) {
  20745. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20746. }
  20747. this._visibilityChanged = true;
  20748. return geometryId;
  20749. }
  20750. /**
  20751. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20752. * this geometry will also be removed as a side effect.
  20753. *
  20754. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20755. * @return {BatchedMesh} A reference to this batched mesh.
  20756. */
  20757. deleteGeometry( geometryId ) {
  20758. const geometryInfoList = this._geometryInfo;
  20759. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20760. return this;
  20761. }
  20762. // delete any instances associated with this geometry
  20763. const instanceInfo = this._instanceInfo;
  20764. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20765. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20766. this.deleteInstance( i );
  20767. }
  20768. }
  20769. geometryInfoList[ geometryId ].active = false;
  20770. this._availableGeometryIds.push( geometryId );
  20771. this._visibilityChanged = true;
  20772. return this;
  20773. }
  20774. /**
  20775. * Deletes an existing instance from the batch using the given ID.
  20776. *
  20777. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20778. * @return {BatchedMesh} A reference to this batched mesh.
  20779. */
  20780. deleteInstance( instanceId ) {
  20781. this.validateInstanceId( instanceId );
  20782. this._instanceInfo[ instanceId ].active = false;
  20783. this._availableInstanceIds.push( instanceId );
  20784. this._visibilityChanged = true;
  20785. return this;
  20786. }
  20787. /**
  20788. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  20789. * previously deleted geometry, freeing up space to add new geometry.
  20790. *
  20791. * @return {BatchedMesh} A reference to this batched mesh.
  20792. */
  20793. optimize() {
  20794. // track the next indices to copy data to
  20795. let nextVertexStart = 0;
  20796. let nextIndexStart = 0;
  20797. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20798. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20799. const geometryInfoList = this._geometryInfo;
  20800. const indices = geometryInfoList
  20801. .map( ( e, i ) => i )
  20802. .sort( ( a, b ) => {
  20803. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20804. } );
  20805. const geometry = this.geometry;
  20806. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20807. // if a geometry range is inactive then don't copy anything
  20808. const index = indices[ i ];
  20809. const geometryInfo = geometryInfoList[ index ];
  20810. if ( geometryInfo.active === false ) {
  20811. continue;
  20812. }
  20813. // if a geometry contains an index buffer then shift it, as well
  20814. if ( geometry.index !== null ) {
  20815. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20816. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20817. const index = geometry.index;
  20818. const array = index.array;
  20819. // shift the index pointers based on how the vertex data will shift
  20820. // adjusting the index must happen first so the original vertex start value is available
  20821. const elementDelta = nextVertexStart - vertexStart;
  20822. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20823. array[ j ] = array[ j ] + elementDelta;
  20824. }
  20825. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20826. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20827. index.needsUpdate = true;
  20828. geometryInfo.indexStart = nextIndexStart;
  20829. }
  20830. nextIndexStart += geometryInfo.reservedIndexCount;
  20831. }
  20832. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20833. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20834. const { vertexStart, reservedVertexCount } = geometryInfo;
  20835. const attributes = geometry.attributes;
  20836. for ( const key in attributes ) {
  20837. const attribute = attributes[ key ];
  20838. const { array, itemSize } = attribute;
  20839. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20840. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20841. attribute.needsUpdate = true;
  20842. }
  20843. geometryInfo.vertexStart = nextVertexStart;
  20844. }
  20845. nextVertexStart += geometryInfo.reservedVertexCount;
  20846. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20847. }
  20848. this._nextIndexStart = nextIndexStart;
  20849. this._nextVertexStart = nextVertexStart;
  20850. this._visibilityChanged = true;
  20851. return this;
  20852. }
  20853. /**
  20854. * Returns the bounding box for the given geometry.
  20855. *
  20856. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20857. * @param {Box3} target - The target object that is used to store the method's result.
  20858. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20859. */
  20860. getBoundingBoxAt( geometryId, target ) {
  20861. if ( geometryId >= this._geometryCount ) {
  20862. return null;
  20863. }
  20864. // compute bounding box
  20865. const geometry = this.geometry;
  20866. const geometryInfo = this._geometryInfo[ geometryId ];
  20867. if ( geometryInfo.boundingBox === null ) {
  20868. const box = new Box3();
  20869. const index = geometry.index;
  20870. const position = geometry.attributes.position;
  20871. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20872. let iv = i;
  20873. if ( index ) {
  20874. iv = index.getX( iv );
  20875. }
  20876. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20877. }
  20878. geometryInfo.boundingBox = box;
  20879. }
  20880. target.copy( geometryInfo.boundingBox );
  20881. return target;
  20882. }
  20883. /**
  20884. * Returns the bounding sphere for the given geometry.
  20885. *
  20886. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20887. * @param {Sphere} target - The target object that is used to store the method's result.
  20888. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20889. */
  20890. getBoundingSphereAt( geometryId, target ) {
  20891. if ( geometryId >= this._geometryCount ) {
  20892. return null;
  20893. }
  20894. // compute bounding sphere
  20895. const geometry = this.geometry;
  20896. const geometryInfo = this._geometryInfo[ geometryId ];
  20897. if ( geometryInfo.boundingSphere === null ) {
  20898. const sphere = new Sphere();
  20899. this.getBoundingBoxAt( geometryId, _box$1 );
  20900. _box$1.getCenter( sphere.center );
  20901. const index = geometry.index;
  20902. const position = geometry.attributes.position;
  20903. let maxRadiusSq = 0;
  20904. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20905. let iv = i;
  20906. if ( index ) {
  20907. iv = index.getX( iv );
  20908. }
  20909. _vector$5.fromBufferAttribute( position, iv );
  20910. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20911. }
  20912. sphere.radius = Math.sqrt( maxRadiusSq );
  20913. geometryInfo.boundingSphere = sphere;
  20914. }
  20915. target.copy( geometryInfo.boundingSphere );
  20916. return target;
  20917. }
  20918. /**
  20919. * Sets the given local transformation matrix to the defined instance.
  20920. * Negatively scaled matrices are not supported.
  20921. *
  20922. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20923. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20924. * @return {BatchedMesh} A reference to this batched mesh.
  20925. */
  20926. setMatrixAt( instanceId, matrix ) {
  20927. this.validateInstanceId( instanceId );
  20928. const matricesTexture = this._matricesTexture;
  20929. const matricesArray = this._matricesTexture.image.data;
  20930. matrix.toArray( matricesArray, instanceId * 16 );
  20931. matricesTexture.needsUpdate = true;
  20932. return this;
  20933. }
  20934. /**
  20935. * Returns the local transformation matrix of the defined instance.
  20936. *
  20937. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20938. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20939. * @return {Matrix4} The instance's local transformation matrix.
  20940. */
  20941. getMatrixAt( instanceId, matrix ) {
  20942. this.validateInstanceId( instanceId );
  20943. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20944. }
  20945. /**
  20946. * Sets the given color to the defined instance.
  20947. *
  20948. * @param {number} instanceId - The ID of an instance to set the color of.
  20949. * @param {Color|Vector4} color - The color to set the instance to. Use a `Vector4` to also define alpha.
  20950. * @return {BatchedMesh} A reference to this batched mesh.
  20951. */
  20952. setColorAt( instanceId, color ) {
  20953. this.validateInstanceId( instanceId );
  20954. if ( this._colorsTexture === null ) {
  20955. this._initColorsTexture();
  20956. }
  20957. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20958. this._colorsTexture.needsUpdate = true;
  20959. return this;
  20960. }
  20961. /**
  20962. * Returns the color of the defined instance.
  20963. *
  20964. * @param {number} instanceId - The ID of an instance to get the color of.
  20965. * @param {Color|Vector4} color - The target object that is used to store the method's result.
  20966. * @return {Color|Vector4} The instance's color. Use a `Vector4` to also retrieve alpha.
  20967. */
  20968. getColorAt( instanceId, color ) {
  20969. this.validateInstanceId( instanceId );
  20970. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20971. }
  20972. /**
  20973. * Sets the visibility of the instance.
  20974. *
  20975. * @param {number} instanceId - The id of the instance to set the visibility of.
  20976. * @param {boolean} visible - Whether the instance is visible or not.
  20977. * @return {BatchedMesh} A reference to this batched mesh.
  20978. */
  20979. setVisibleAt( instanceId, visible ) {
  20980. this.validateInstanceId( instanceId );
  20981. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20982. return this;
  20983. }
  20984. this._instanceInfo[ instanceId ].visible = visible;
  20985. this._visibilityChanged = true;
  20986. return this;
  20987. }
  20988. /**
  20989. * Returns the visibility state of the defined instance.
  20990. *
  20991. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20992. * @return {boolean} Whether the instance is visible or not.
  20993. */
  20994. getVisibleAt( instanceId ) {
  20995. this.validateInstanceId( instanceId );
  20996. return this._instanceInfo[ instanceId ].visible;
  20997. }
  20998. /**
  20999. * Sets the geometry ID of the instance at the given index.
  21000. *
  21001. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  21002. * @param {number} geometryId - The geometry ID to be use by the instance.
  21003. * @return {BatchedMesh} A reference to this batched mesh.
  21004. */
  21005. setGeometryIdAt( instanceId, geometryId ) {
  21006. this.validateInstanceId( instanceId );
  21007. this.validateGeometryId( geometryId );
  21008. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  21009. return this;
  21010. }
  21011. /**
  21012. * Returns the geometry ID of the defined instance.
  21013. *
  21014. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  21015. * @return {number} The instance's geometry ID.
  21016. */
  21017. getGeometryIdAt( instanceId ) {
  21018. this.validateInstanceId( instanceId );
  21019. return this._instanceInfo[ instanceId ].geometryIndex;
  21020. }
  21021. /**
  21022. * Get the range representing the subset of triangles related to the attached geometry,
  21023. * indicating the starting offset and count, or `null` if invalid.
  21024. *
  21025. * @param {number} geometryId - The id of the geometry to get the range of.
  21026. * @param {Object} [target] - The target object that is used to store the method's result.
  21027. * @return {{
  21028. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  21029. * indexStart:number,indexCount:number,reservedIndexCount:number,
  21030. * start:number,count:number
  21031. * }} The result object with range data.
  21032. */
  21033. getGeometryRangeAt( geometryId, target = {} ) {
  21034. this.validateGeometryId( geometryId );
  21035. const geometryInfo = this._geometryInfo[ geometryId ];
  21036. target.vertexStart = geometryInfo.vertexStart;
  21037. target.vertexCount = geometryInfo.vertexCount;
  21038. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  21039. target.indexStart = geometryInfo.indexStart;
  21040. target.indexCount = geometryInfo.indexCount;
  21041. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  21042. target.start = geometryInfo.start;
  21043. target.count = geometryInfo.count;
  21044. return target;
  21045. }
  21046. /**
  21047. * Resizes the necessary buffers to support the provided number of instances.
  21048. * If the provided arguments shrink the number of instances but there are not enough
  21049. * unused Ids at the end of the list then an error is thrown.
  21050. *
  21051. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  21052. */
  21053. setInstanceCount( maxInstanceCount ) {
  21054. // shrink the available instances as much as possible
  21055. const availableInstanceIds = this._availableInstanceIds;
  21056. const instanceInfo = this._instanceInfo;
  21057. availableInstanceIds.sort( ascIdSort );
  21058. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  21059. instanceInfo.pop();
  21060. availableInstanceIds.pop();
  21061. }
  21062. // throw an error if it can't be shrunk to the desired size
  21063. if ( maxInstanceCount < instanceInfo.length ) {
  21064. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  21065. }
  21066. // copy the multi draw counts
  21067. const multiDrawCounts = new Int32Array( maxInstanceCount );
  21068. const multiDrawStarts = new Int32Array( maxInstanceCount );
  21069. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  21070. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  21071. this._multiDrawCounts = multiDrawCounts;
  21072. this._multiDrawStarts = multiDrawStarts;
  21073. this._maxInstanceCount = maxInstanceCount;
  21074. // update texture data for instance sampling
  21075. const indirectTexture = this._indirectTexture;
  21076. const matricesTexture = this._matricesTexture;
  21077. const colorsTexture = this._colorsTexture;
  21078. indirectTexture.dispose();
  21079. this._initIndirectTexture();
  21080. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  21081. matricesTexture.dispose();
  21082. this._initMatricesTexture();
  21083. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  21084. if ( colorsTexture ) {
  21085. colorsTexture.dispose();
  21086. this._initColorsTexture();
  21087. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  21088. }
  21089. }
  21090. /**
  21091. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  21092. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  21093. * end of the geometry attributes then an error is thrown.
  21094. *
  21095. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  21096. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  21097. */
  21098. setGeometrySize( maxVertexCount, maxIndexCount ) {
  21099. // Check if we can shrink to the requested vertex attribute size
  21100. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  21101. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  21102. if ( requiredVertexLength > maxVertexCount ) {
  21103. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  21104. }
  21105. // Check if we can shrink to the requested index attribute size
  21106. if ( this.geometry.index ) {
  21107. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  21108. if ( requiredIndexLength > maxIndexCount ) {
  21109. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  21110. }
  21111. }
  21112. //
  21113. // dispose of the previous geometry
  21114. const oldGeometry = this.geometry;
  21115. oldGeometry.dispose();
  21116. // recreate the geometry needed based on the previous variant
  21117. this._maxVertexCount = maxVertexCount;
  21118. this._maxIndexCount = maxIndexCount;
  21119. if ( this._geometryInitialized ) {
  21120. this._geometryInitialized = false;
  21121. this.geometry = new BufferGeometry();
  21122. this._initializeGeometry( oldGeometry );
  21123. }
  21124. // copy data from the previous geometry
  21125. const geometry = this.geometry;
  21126. if ( oldGeometry.index ) {
  21127. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  21128. }
  21129. for ( const key in oldGeometry.attributes ) {
  21130. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  21131. }
  21132. }
  21133. raycast( raycaster, intersects ) {
  21134. const instanceInfo = this._instanceInfo;
  21135. const geometryInfoList = this._geometryInfo;
  21136. const matrixWorld = this.matrixWorld;
  21137. const batchGeometry = this.geometry;
  21138. // iterate over each geometry
  21139. _mesh.material = this.material;
  21140. _mesh.geometry.index = batchGeometry.index;
  21141. _mesh.geometry.attributes = batchGeometry.attributes;
  21142. if ( _mesh.geometry.boundingBox === null ) {
  21143. _mesh.geometry.boundingBox = new Box3();
  21144. }
  21145. if ( _mesh.geometry.boundingSphere === null ) {
  21146. _mesh.geometry.boundingSphere = new Sphere();
  21147. }
  21148. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21149. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  21150. continue;
  21151. }
  21152. const geometryId = instanceInfo[ i ].geometryIndex;
  21153. const geometryInfo = geometryInfoList[ geometryId ];
  21154. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  21155. // get the intersects
  21156. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  21157. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  21158. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  21159. _mesh.raycast( raycaster, _batchIntersects );
  21160. // add batch id to the intersects
  21161. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  21162. const intersect = _batchIntersects[ j ];
  21163. intersect.object = this;
  21164. intersect.batchId = i;
  21165. intersects.push( intersect );
  21166. }
  21167. _batchIntersects.length = 0;
  21168. }
  21169. _mesh.material = null;
  21170. _mesh.geometry.index = null;
  21171. _mesh.geometry.attributes = {};
  21172. _mesh.geometry.setDrawRange( 0, Infinity );
  21173. }
  21174. copy( source ) {
  21175. super.copy( source );
  21176. this.geometry = source.geometry.clone();
  21177. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  21178. this.sortObjects = source.sortObjects;
  21179. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  21180. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  21181. this._geometryInfo = source._geometryInfo.map( info => ( {
  21182. ...info,
  21183. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  21184. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  21185. } ) );
  21186. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  21187. this._availableInstanceIds = source._availableInstanceIds.slice();
  21188. this._availableGeometryIds = source._availableGeometryIds.slice();
  21189. this._nextIndexStart = source._nextIndexStart;
  21190. this._nextVertexStart = source._nextVertexStart;
  21191. this._geometryCount = source._geometryCount;
  21192. this._maxInstanceCount = source._maxInstanceCount;
  21193. this._maxVertexCount = source._maxVertexCount;
  21194. this._maxIndexCount = source._maxIndexCount;
  21195. this._geometryInitialized = source._geometryInitialized;
  21196. this._multiDrawCounts = source._multiDrawCounts.slice();
  21197. this._multiDrawStarts = source._multiDrawStarts.slice();
  21198. this._indirectTexture = source._indirectTexture.clone();
  21199. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  21200. this._matricesTexture = source._matricesTexture.clone();
  21201. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  21202. if ( this._colorsTexture !== null ) {
  21203. this._colorsTexture = source._colorsTexture.clone();
  21204. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  21205. }
  21206. return this;
  21207. }
  21208. /**
  21209. * Frees the GPU-related resources allocated by this instance. Call this
  21210. * method whenever this instance is no longer used in your app.
  21211. */
  21212. dispose() {
  21213. // Assuming the geometry is not shared with other meshes
  21214. this.geometry.dispose();
  21215. this._matricesTexture.dispose();
  21216. this._matricesTexture = null;
  21217. this._indirectTexture.dispose();
  21218. this._indirectTexture = null;
  21219. if ( this._colorsTexture !== null ) {
  21220. this._colorsTexture.dispose();
  21221. this._colorsTexture = null;
  21222. }
  21223. }
  21224. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  21225. // if visibility has not changed and frustum culling and object sorting is not required
  21226. // then skip iterating over all items
  21227. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  21228. return;
  21229. }
  21230. // the indexed version of the multi draw function requires specifying the start
  21231. // offset in bytes.
  21232. const index = geometry.getIndex();
  21233. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  21234. const instanceInfo = this._instanceInfo;
  21235. const multiDrawStarts = this._multiDrawStarts;
  21236. const multiDrawCounts = this._multiDrawCounts;
  21237. const geometryInfoList = this._geometryInfo;
  21238. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  21239. const indirectTexture = this._indirectTexture;
  21240. const indirectArray = indirectTexture.image.data;
  21241. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  21242. // prepare the frustum in the local frame
  21243. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  21244. _matrix$1
  21245. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  21246. .multiply( this.matrixWorld );
  21247. _frustum.setFromProjectionMatrix(
  21248. _matrix$1,
  21249. camera.coordinateSystem,
  21250. camera.reversedDepth
  21251. );
  21252. }
  21253. let multiDrawCount = 0;
  21254. if ( this.sortObjects ) {
  21255. // get the camera position in the local frame
  21256. _matrix$1.copy( this.matrixWorld ).invert();
  21257. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  21258. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  21259. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21260. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21261. const geometryId = instanceInfo[ i ].geometryIndex;
  21262. // get the bounds in world space
  21263. this.getMatrixAt( i, _matrix$1 );
  21264. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21265. // determine whether the batched geometry is within the frustum
  21266. let culled = false;
  21267. if ( perObjectFrustumCulled ) {
  21268. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21269. }
  21270. if ( ! culled ) {
  21271. // get the distance from camera used for sorting
  21272. const geometryInfo = geometryInfoList[ geometryId ];
  21273. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  21274. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  21275. }
  21276. }
  21277. }
  21278. // Sort the draw ranges and prep for rendering
  21279. const list = _renderList.list;
  21280. const customSort = this.customSort;
  21281. if ( customSort === null ) {
  21282. list.sort( material.transparent ? sortTransparent : sortOpaque );
  21283. } else {
  21284. customSort.call( this, list, camera );
  21285. }
  21286. for ( let i = 0, l = list.length; i < l; i ++ ) {
  21287. const item = list[ i ];
  21288. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  21289. multiDrawCounts[ multiDrawCount ] = item.count;
  21290. indirectArray[ multiDrawCount ] = item.index;
  21291. multiDrawCount ++;
  21292. }
  21293. _renderList.reset();
  21294. } else {
  21295. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21296. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21297. const geometryId = instanceInfo[ i ].geometryIndex;
  21298. // determine whether the batched geometry is within the frustum
  21299. let culled = false;
  21300. if ( perObjectFrustumCulled ) {
  21301. // get the bounds in world space
  21302. this.getMatrixAt( i, _matrix$1 );
  21303. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21304. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21305. }
  21306. if ( ! culled ) {
  21307. const geometryInfo = geometryInfoList[ geometryId ];
  21308. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  21309. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  21310. indirectArray[ multiDrawCount ] = i;
  21311. multiDrawCount ++;
  21312. }
  21313. }
  21314. }
  21315. }
  21316. indirectTexture.needsUpdate = true;
  21317. this._multiDrawCount = multiDrawCount;
  21318. this._visibilityChanged = false;
  21319. }
  21320. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  21321. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  21322. }
  21323. }
  21324. /**
  21325. * A material for rendering line primitives.
  21326. *
  21327. * Materials define the appearance of renderable 3D objects.
  21328. *
  21329. * ```js
  21330. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  21331. * ```
  21332. *
  21333. * @augments Material
  21334. */
  21335. class LineBasicMaterial extends Material {
  21336. /**
  21337. * Constructs a new line basic material.
  21338. *
  21339. * @param {Object} [parameters] - An object with one or more properties
  21340. * defining the material's appearance. Any property of the material
  21341. * (including any property from inherited materials) can be passed
  21342. * in here. Color values can be passed any type of value accepted
  21343. * by {@link Color#set}.
  21344. */
  21345. constructor( parameters ) {
  21346. super();
  21347. /**
  21348. * This flag can be used for type testing.
  21349. *
  21350. * @type {boolean}
  21351. * @readonly
  21352. * @default true
  21353. */
  21354. this.isLineBasicMaterial = true;
  21355. this.type = 'LineBasicMaterial';
  21356. /**
  21357. * Color of the material.
  21358. *
  21359. * @type {Color}
  21360. * @default (1,1,1)
  21361. */
  21362. this.color = new Color( 0xffffff );
  21363. /**
  21364. * Sets the color of the lines using data from a texture. The texture map
  21365. * color is modulated by the diffuse `color`.
  21366. *
  21367. * @type {?Texture}
  21368. * @default null
  21369. */
  21370. this.map = null;
  21371. /**
  21372. * Controls line thickness or lines.
  21373. *
  21374. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21375. * ignore this setting and always render line primitives with a
  21376. * width of one pixel.
  21377. *
  21378. * @type {number}
  21379. * @default 1
  21380. */
  21381. this.linewidth = 1;
  21382. /**
  21383. * Defines appearance of line ends.
  21384. *
  21385. * Can only be used with {@link SVGRenderer}.
  21386. *
  21387. * @type {('butt'|'round'|'square')}
  21388. * @default 'round'
  21389. */
  21390. this.linecap = 'round';
  21391. /**
  21392. * Defines appearance of line joints.
  21393. *
  21394. * Can only be used with {@link SVGRenderer}.
  21395. *
  21396. * @type {('round'|'bevel'|'miter')}
  21397. * @default 'round'
  21398. */
  21399. this.linejoin = 'round';
  21400. /**
  21401. * Whether the material is affected by fog or not.
  21402. *
  21403. * @type {boolean}
  21404. * @default true
  21405. */
  21406. this.fog = true;
  21407. this.setValues( parameters );
  21408. }
  21409. copy( source ) {
  21410. super.copy( source );
  21411. this.color.copy( source.color );
  21412. this.map = source.map;
  21413. this.linewidth = source.linewidth;
  21414. this.linecap = source.linecap;
  21415. this.linejoin = source.linejoin;
  21416. this.fog = source.fog;
  21417. return this;
  21418. }
  21419. }
  21420. const _vStart = /*@__PURE__*/ new Vector3();
  21421. const _vEnd = /*@__PURE__*/ new Vector3();
  21422. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21423. const _ray$1 = /*@__PURE__*/ new Ray();
  21424. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21425. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21426. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21427. /**
  21428. * A continuous line. The line are rendered by connecting consecutive
  21429. * vertices with straight lines.
  21430. *
  21431. * ```js
  21432. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21433. *
  21434. * const points = [];
  21435. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21436. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21437. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21438. *
  21439. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21440. *
  21441. * const line = new THREE.Line( geometry, material );
  21442. * scene.add( line );
  21443. * ```
  21444. *
  21445. * @augments Object3D
  21446. */
  21447. class Line extends Object3D {
  21448. /**
  21449. * Constructs a new line.
  21450. *
  21451. * @param {BufferGeometry} [geometry] - The line geometry.
  21452. * @param {Material|Array<Material>} [material] - The line material.
  21453. */
  21454. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21455. super();
  21456. /**
  21457. * This flag can be used for type testing.
  21458. *
  21459. * @type {boolean}
  21460. * @readonly
  21461. * @default true
  21462. */
  21463. this.isLine = true;
  21464. this.type = 'Line';
  21465. /**
  21466. * The line geometry.
  21467. *
  21468. * @type {BufferGeometry}
  21469. */
  21470. this.geometry = geometry;
  21471. /**
  21472. * The line material.
  21473. *
  21474. * @type {Material|Array<Material>}
  21475. * @default LineBasicMaterial
  21476. */
  21477. this.material = material;
  21478. /**
  21479. * A dictionary representing the morph targets in the geometry. The key is the
  21480. * morph targets name, the value its attribute index. This member is `undefined`
  21481. * by default and only set when morph targets are detected in the geometry.
  21482. *
  21483. * @type {Object<string,number>|undefined}
  21484. * @default undefined
  21485. */
  21486. this.morphTargetDictionary = undefined;
  21487. /**
  21488. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21489. * is applied. This member is `undefined` by default and only set when morph targets are
  21490. * detected in the geometry.
  21491. *
  21492. * @type {Array<number>|undefined}
  21493. * @default undefined
  21494. */
  21495. this.morphTargetInfluences = undefined;
  21496. this.updateMorphTargets();
  21497. }
  21498. copy( source, recursive ) {
  21499. super.copy( source, recursive );
  21500. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21501. this.geometry = source.geometry;
  21502. return this;
  21503. }
  21504. /**
  21505. * Computes an array of distance values which are necessary for rendering dashed lines.
  21506. * For each vertex in the geometry, the method calculates the cumulative length from the
  21507. * current point to the very beginning of the line.
  21508. *
  21509. * @return {Line} A reference to this line.
  21510. */
  21511. computeLineDistances() {
  21512. const geometry = this.geometry;
  21513. // we assume non-indexed geometry
  21514. if ( geometry.index === null ) {
  21515. const positionAttribute = geometry.attributes.position;
  21516. const lineDistances = [ 0 ];
  21517. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21518. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21519. _vEnd.fromBufferAttribute( positionAttribute, i );
  21520. lineDistances[ i ] = lineDistances[ i - 1 ];
  21521. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21522. }
  21523. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21524. } else {
  21525. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21526. }
  21527. return this;
  21528. }
  21529. /**
  21530. * Computes intersection points between a casted ray and this line.
  21531. *
  21532. * @param {Raycaster} raycaster - The raycaster.
  21533. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21534. */
  21535. raycast( raycaster, intersects ) {
  21536. const geometry = this.geometry;
  21537. const matrixWorld = this.matrixWorld;
  21538. const threshold = raycaster.params.Line.threshold;
  21539. const drawRange = geometry.drawRange;
  21540. // Checking boundingSphere distance to ray
  21541. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21542. _sphere$1.copy( geometry.boundingSphere );
  21543. _sphere$1.applyMatrix4( matrixWorld );
  21544. _sphere$1.radius += threshold;
  21545. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21546. //
  21547. _inverseMatrix$1.copy( matrixWorld ).invert();
  21548. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21549. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21550. const localThresholdSq = localThreshold * localThreshold;
  21551. const step = this.isLineSegments ? 2 : 1;
  21552. const index = geometry.index;
  21553. const attributes = geometry.attributes;
  21554. const positionAttribute = attributes.position;
  21555. if ( index !== null ) {
  21556. const start = Math.max( 0, drawRange.start );
  21557. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21558. for ( let i = start, l = end - 1; i < l; i += step ) {
  21559. const a = index.getX( i );
  21560. const b = index.getX( i + 1 );
  21561. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21562. if ( intersect ) {
  21563. intersects.push( intersect );
  21564. }
  21565. }
  21566. if ( this.isLineLoop ) {
  21567. const a = index.getX( end - 1 );
  21568. const b = index.getX( start );
  21569. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21570. if ( intersect ) {
  21571. intersects.push( intersect );
  21572. }
  21573. }
  21574. } else {
  21575. const start = Math.max( 0, drawRange.start );
  21576. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21577. for ( let i = start, l = end - 1; i < l; i += step ) {
  21578. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21579. if ( intersect ) {
  21580. intersects.push( intersect );
  21581. }
  21582. }
  21583. if ( this.isLineLoop ) {
  21584. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21585. if ( intersect ) {
  21586. intersects.push( intersect );
  21587. }
  21588. }
  21589. }
  21590. }
  21591. /**
  21592. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21593. * to make sure existing morph targets can influence this 3D object.
  21594. */
  21595. updateMorphTargets() {
  21596. const geometry = this.geometry;
  21597. const morphAttributes = geometry.morphAttributes;
  21598. const keys = Object.keys( morphAttributes );
  21599. if ( keys.length > 0 ) {
  21600. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21601. if ( morphAttribute !== undefined ) {
  21602. this.morphTargetInfluences = [];
  21603. this.morphTargetDictionary = {};
  21604. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21605. const name = morphAttribute[ m ].name || String( m );
  21606. this.morphTargetInfluences.push( 0 );
  21607. this.morphTargetDictionary[ name ] = m;
  21608. }
  21609. }
  21610. }
  21611. }
  21612. }
  21613. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21614. const positionAttribute = object.geometry.attributes.position;
  21615. _vStart.fromBufferAttribute( positionAttribute, a );
  21616. _vEnd.fromBufferAttribute( positionAttribute, b );
  21617. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21618. if ( distSq > thresholdSq ) return;
  21619. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21620. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21621. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21622. return {
  21623. distance: distance,
  21624. // What do we want? intersection point on the ray or on the segment??
  21625. // point: raycaster.ray.at( distance ),
  21626. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21627. index: i,
  21628. face: null,
  21629. faceIndex: null,
  21630. barycoord: null,
  21631. object: object
  21632. };
  21633. }
  21634. const _start = /*@__PURE__*/ new Vector3();
  21635. const _end = /*@__PURE__*/ new Vector3();
  21636. /**
  21637. * A series of lines drawn between pairs of vertices.
  21638. *
  21639. * @augments Line
  21640. */
  21641. class LineSegments extends Line {
  21642. /**
  21643. * Constructs a new line segments.
  21644. *
  21645. * @param {BufferGeometry} [geometry] - The line geometry.
  21646. * @param {Material|Array<Material>} [material] - The line material.
  21647. */
  21648. constructor( geometry, material ) {
  21649. super( geometry, material );
  21650. /**
  21651. * This flag can be used for type testing.
  21652. *
  21653. * @type {boolean}
  21654. * @readonly
  21655. * @default true
  21656. */
  21657. this.isLineSegments = true;
  21658. this.type = 'LineSegments';
  21659. }
  21660. computeLineDistances() {
  21661. const geometry = this.geometry;
  21662. // we assume non-indexed geometry
  21663. if ( geometry.index === null ) {
  21664. const positionAttribute = geometry.attributes.position;
  21665. const lineDistances = [];
  21666. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21667. _start.fromBufferAttribute( positionAttribute, i );
  21668. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21669. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21670. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21671. }
  21672. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21673. } else {
  21674. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21675. }
  21676. return this;
  21677. }
  21678. }
  21679. /**
  21680. * A continuous line. This is nearly the same as {@link Line} the only difference
  21681. * is that the last vertex is connected with the first vertex in order to close
  21682. * the line to form a loop.
  21683. *
  21684. * @augments Line
  21685. */
  21686. class LineLoop extends Line {
  21687. /**
  21688. * Constructs a new line loop.
  21689. *
  21690. * @param {BufferGeometry} [geometry] - The line geometry.
  21691. * @param {Material|Array<Material>} [material] - The line material.
  21692. */
  21693. constructor( geometry, material ) {
  21694. super( geometry, material );
  21695. /**
  21696. * This flag can be used for type testing.
  21697. *
  21698. * @type {boolean}
  21699. * @readonly
  21700. * @default true
  21701. */
  21702. this.isLineLoop = true;
  21703. this.type = 'LineLoop';
  21704. }
  21705. }
  21706. /**
  21707. * A material for rendering point primitives.
  21708. *
  21709. * Materials define the appearance of renderable 3D objects.
  21710. *
  21711. * ```js
  21712. * const vertices = [];
  21713. *
  21714. * for ( let i = 0; i < 10000; i ++ ) {
  21715. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21716. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21717. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21718. *
  21719. * vertices.push( x, y, z );
  21720. * }
  21721. *
  21722. * const geometry = new THREE.BufferGeometry();
  21723. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21724. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21725. * const points = new THREE.Points( geometry, material );
  21726. * scene.add( points );
  21727. * ```
  21728. *
  21729. * @augments Material
  21730. */
  21731. class PointsMaterial extends Material {
  21732. /**
  21733. * Constructs a new points material.
  21734. *
  21735. * @param {Object} [parameters] - An object with one or more properties
  21736. * defining the material's appearance. Any property of the material
  21737. * (including any property from inherited materials) can be passed
  21738. * in here. Color values can be passed any type of value accepted
  21739. * by {@link Color#set}.
  21740. */
  21741. constructor( parameters ) {
  21742. super();
  21743. /**
  21744. * This flag can be used for type testing.
  21745. *
  21746. * @type {boolean}
  21747. * @readonly
  21748. * @default true
  21749. */
  21750. this.isPointsMaterial = true;
  21751. this.type = 'PointsMaterial';
  21752. /**
  21753. * Color of the material.
  21754. *
  21755. * @type {Color}
  21756. * @default (1,1,1)
  21757. */
  21758. this.color = new Color( 0xffffff );
  21759. /**
  21760. * The color map. May optionally include an alpha channel, typically combined
  21761. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21762. * color is modulated by the diffuse `color`.
  21763. *
  21764. * @type {?Texture}
  21765. * @default null
  21766. */
  21767. this.map = null;
  21768. /**
  21769. * The alpha map is a grayscale texture that controls the opacity across the
  21770. * surface (black: fully transparent; white: fully opaque).
  21771. *
  21772. * Only the color of the texture is used, ignoring the alpha channel if one
  21773. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21774. * when sampling this texture due to the extra bit of precision provided for
  21775. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21776. * luminance/alpha textures will also still work as expected.
  21777. *
  21778. * @type {?Texture}
  21779. * @default null
  21780. */
  21781. this.alphaMap = null;
  21782. /**
  21783. * Defines the size of the points in pixels.
  21784. *
  21785. * 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).
  21786. *
  21787. * @type {number}
  21788. * @default 1
  21789. */
  21790. this.size = 1;
  21791. /**
  21792. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21793. *
  21794. * @type {boolean}
  21795. * @default true
  21796. */
  21797. this.sizeAttenuation = true;
  21798. /**
  21799. * Whether the material is affected by fog or not.
  21800. *
  21801. * @type {boolean}
  21802. * @default true
  21803. */
  21804. this.fog = true;
  21805. this.setValues( parameters );
  21806. }
  21807. copy( source ) {
  21808. super.copy( source );
  21809. this.color.copy( source.color );
  21810. this.map = source.map;
  21811. this.alphaMap = source.alphaMap;
  21812. this.size = source.size;
  21813. this.sizeAttenuation = source.sizeAttenuation;
  21814. this.fog = source.fog;
  21815. return this;
  21816. }
  21817. }
  21818. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21819. const _ray = /*@__PURE__*/ new Ray();
  21820. const _sphere = /*@__PURE__*/ new Sphere();
  21821. const _position$2 = /*@__PURE__*/ new Vector3();
  21822. /**
  21823. * A class for displaying points or point clouds.
  21824. *
  21825. * @augments Object3D
  21826. */
  21827. class Points extends Object3D {
  21828. /**
  21829. * Constructs a new point cloud.
  21830. *
  21831. * @param {BufferGeometry} [geometry] - The points geometry.
  21832. * @param {Material|Array<Material>} [material] - The points material.
  21833. */
  21834. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21835. super();
  21836. /**
  21837. * This flag can be used for type testing.
  21838. *
  21839. * @type {boolean}
  21840. * @readonly
  21841. * @default true
  21842. */
  21843. this.isPoints = true;
  21844. this.type = 'Points';
  21845. /**
  21846. * The points geometry.
  21847. *
  21848. * @type {BufferGeometry}
  21849. */
  21850. this.geometry = geometry;
  21851. /**
  21852. * The line material.
  21853. *
  21854. * @type {Material|Array<Material>}
  21855. * @default PointsMaterial
  21856. */
  21857. this.material = material;
  21858. /**
  21859. * A dictionary representing the morph targets in the geometry. The key is the
  21860. * morph targets name, the value its attribute index. This member is `undefined`
  21861. * by default and only set when morph targets are detected in the geometry.
  21862. *
  21863. * @type {Object<string,number>|undefined}
  21864. * @default undefined
  21865. */
  21866. this.morphTargetDictionary = undefined;
  21867. /**
  21868. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21869. * is applied. This member is `undefined` by default and only set when morph targets are
  21870. * detected in the geometry.
  21871. *
  21872. * @type {Array<number>|undefined}
  21873. * @default undefined
  21874. */
  21875. this.morphTargetInfluences = undefined;
  21876. this.updateMorphTargets();
  21877. }
  21878. copy( source, recursive ) {
  21879. super.copy( source, recursive );
  21880. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21881. this.geometry = source.geometry;
  21882. return this;
  21883. }
  21884. /**
  21885. * Computes intersection points between a casted ray and this point cloud.
  21886. *
  21887. * @param {Raycaster} raycaster - The raycaster.
  21888. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21889. */
  21890. raycast( raycaster, intersects ) {
  21891. const geometry = this.geometry;
  21892. const matrixWorld = this.matrixWorld;
  21893. const threshold = raycaster.params.Points.threshold;
  21894. const drawRange = geometry.drawRange;
  21895. // Checking boundingSphere distance to ray
  21896. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21897. _sphere.copy( geometry.boundingSphere );
  21898. _sphere.applyMatrix4( matrixWorld );
  21899. _sphere.radius += threshold;
  21900. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21901. //
  21902. _inverseMatrix.copy( matrixWorld ).invert();
  21903. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21904. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21905. const localThresholdSq = localThreshold * localThreshold;
  21906. const index = geometry.index;
  21907. const attributes = geometry.attributes;
  21908. const positionAttribute = attributes.position;
  21909. if ( index !== null ) {
  21910. const start = Math.max( 0, drawRange.start );
  21911. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21912. for ( let i = start, il = end; i < il; i ++ ) {
  21913. const a = index.getX( i );
  21914. _position$2.fromBufferAttribute( positionAttribute, a );
  21915. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21916. }
  21917. } else {
  21918. const start = Math.max( 0, drawRange.start );
  21919. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21920. for ( let i = start, l = end; i < l; i ++ ) {
  21921. _position$2.fromBufferAttribute( positionAttribute, i );
  21922. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21923. }
  21924. }
  21925. }
  21926. /**
  21927. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21928. * to make sure existing morph targets can influence this 3D object.
  21929. */
  21930. updateMorphTargets() {
  21931. const geometry = this.geometry;
  21932. const morphAttributes = geometry.morphAttributes;
  21933. const keys = Object.keys( morphAttributes );
  21934. if ( keys.length > 0 ) {
  21935. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21936. if ( morphAttribute !== undefined ) {
  21937. this.morphTargetInfluences = [];
  21938. this.morphTargetDictionary = {};
  21939. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21940. const name = morphAttribute[ m ].name || String( m );
  21941. this.morphTargetInfluences.push( 0 );
  21942. this.morphTargetDictionary[ name ] = m;
  21943. }
  21944. }
  21945. }
  21946. }
  21947. }
  21948. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21949. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21950. if ( rayPointDistanceSq < localThresholdSq ) {
  21951. const intersectPoint = new Vector3();
  21952. _ray.closestPointToPoint( point, intersectPoint );
  21953. intersectPoint.applyMatrix4( matrixWorld );
  21954. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21955. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21956. intersects.push( {
  21957. distance: distance,
  21958. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21959. point: intersectPoint,
  21960. index: index,
  21961. face: null,
  21962. faceIndex: null,
  21963. barycoord: null,
  21964. object: object
  21965. } );
  21966. }
  21967. }
  21968. /**
  21969. * A texture for use with a video.
  21970. *
  21971. * ```js
  21972. * // assuming you have created a HTML video element with id="video"
  21973. * const video = document.getElementById( 'video' );
  21974. * const texture = new THREE.VideoTexture( video );
  21975. * ```
  21976. *
  21977. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21978. * set to THREE.SRGBColorSpace.
  21979. *
  21980. * Note: After the initial use of a texture, its dimensions, format, and type
  21981. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21982. *
  21983. * @augments Texture
  21984. */
  21985. class VideoTexture extends Texture {
  21986. /**
  21987. * Constructs a new video texture.
  21988. *
  21989. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21990. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21991. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21992. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21993. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21994. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21995. * @param {number} [format=RGBAFormat] - The texture format.
  21996. * @param {number} [type=UnsignedByteType] - The texture type.
  21997. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21998. */
  21999. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  22000. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22001. /**
  22002. * This flag can be used for type testing.
  22003. *
  22004. * @type {boolean}
  22005. * @readonly
  22006. * @default true
  22007. */
  22008. this.isVideoTexture = true;
  22009. /**
  22010. * Whether to generate mipmaps (if possible) for a texture.
  22011. *
  22012. * Overwritten and set to `false` by default.
  22013. *
  22014. * @type {boolean}
  22015. * @default false
  22016. */
  22017. this.generateMipmaps = false;
  22018. /**
  22019. * The video frame request callback identifier, which is a positive integer.
  22020. *
  22021. * Value of 0 represents no scheduled rVFC.
  22022. *
  22023. * @private
  22024. * @type {number}
  22025. */
  22026. this._requestVideoFrameCallbackId = 0;
  22027. const scope = this;
  22028. function updateVideo() {
  22029. scope.needsUpdate = true;
  22030. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  22031. }
  22032. if ( 'requestVideoFrameCallback' in video ) {
  22033. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  22034. }
  22035. }
  22036. clone() {
  22037. return new this.constructor( this.image ).copy( this );
  22038. }
  22039. /**
  22040. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  22041. * to `true` every time a new frame is available.
  22042. *
  22043. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  22044. */
  22045. update() {
  22046. const video = this.image;
  22047. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  22048. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  22049. this.needsUpdate = true;
  22050. }
  22051. }
  22052. dispose() {
  22053. if ( this._requestVideoFrameCallbackId !== 0 ) {
  22054. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  22055. this._requestVideoFrameCallbackId = 0;
  22056. }
  22057. super.dispose();
  22058. }
  22059. }
  22060. /**
  22061. * This class can be used as an alternative way to define video data. Instead of using
  22062. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  22063. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  22064. * video frames are decoded with the WebCodecs API.
  22065. *
  22066. * ```js
  22067. * const texture = new THREE.VideoFrameTexture();
  22068. * texture.setFrame( frame );
  22069. * ```
  22070. *
  22071. * @augments VideoTexture
  22072. */
  22073. class VideoFrameTexture extends VideoTexture {
  22074. /**
  22075. * Constructs a new video frame texture.
  22076. *
  22077. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22078. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22079. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22080. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22081. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22082. * @param {number} [format=RGBAFormat] - The texture format.
  22083. * @param {number} [type=UnsignedByteType] - The texture type.
  22084. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22085. */
  22086. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22087. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22088. /**
  22089. * This flag can be used for type testing.
  22090. *
  22091. * @type {boolean}
  22092. * @readonly
  22093. * @default true
  22094. */
  22095. this.isVideoFrameTexture = true;
  22096. }
  22097. /**
  22098. * This method overwritten with an empty implementation since
  22099. * this type of texture is updated via `setFrame()`.
  22100. */
  22101. update() {}
  22102. clone() {
  22103. return new this.constructor().copy( this ); // restoring Texture.clone()
  22104. }
  22105. /**
  22106. * Sets the current frame of the video. This will automatically update the texture
  22107. * so the data can be used for rendering.
  22108. *
  22109. * @param {VideoFrame} frame - The video frame.
  22110. */
  22111. setFrame( frame ) {
  22112. this.image = frame;
  22113. this.needsUpdate = true;
  22114. }
  22115. }
  22116. /**
  22117. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  22118. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  22119. * as a texture for further usage.
  22120. *
  22121. * ```js
  22122. * const pixelRatio = window.devicePixelRatio;
  22123. * const textureSize = 128 * pixelRatio;
  22124. *
  22125. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  22126. *
  22127. * // calculate start position for copying part of the frame data
  22128. * const vector = new Vector2();
  22129. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  22130. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  22131. *
  22132. * renderer.render( scene, camera );
  22133. *
  22134. * // copy part of the rendered frame into the framebuffer texture
  22135. * renderer.copyFramebufferToTexture( frameTexture, vector );
  22136. * ```
  22137. *
  22138. * @augments Texture
  22139. */
  22140. class FramebufferTexture extends Texture {
  22141. /**
  22142. * Constructs a new framebuffer texture.
  22143. *
  22144. * @param {number} [width] - The width of the texture.
  22145. * @param {number} [height] - The height of the texture.
  22146. */
  22147. constructor( width, height ) {
  22148. super( { width, height } );
  22149. /**
  22150. * This flag can be used for type testing.
  22151. *
  22152. * @type {boolean}
  22153. * @readonly
  22154. * @default true
  22155. */
  22156. this.isFramebufferTexture = true;
  22157. /**
  22158. * How the texture is sampled when a texel covers more than one pixel.
  22159. *
  22160. * Overwritten and set to `NearestFilter` by default to disable filtering.
  22161. *
  22162. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  22163. * @default NearestFilter
  22164. */
  22165. this.magFilter = NearestFilter;
  22166. /**
  22167. * How the texture is sampled when a texel covers less than one pixel.
  22168. *
  22169. * Overwritten and set to `NearestFilter` by default to disable filtering.
  22170. *
  22171. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  22172. * @default NearestFilter
  22173. */
  22174. this.minFilter = NearestFilter;
  22175. /**
  22176. * Whether to generate mipmaps (if possible) for a texture.
  22177. *
  22178. * Overwritten and set to `false` by default.
  22179. *
  22180. * @type {boolean}
  22181. * @default false
  22182. */
  22183. this.generateMipmaps = false;
  22184. this.needsUpdate = true;
  22185. }
  22186. }
  22187. /**
  22188. * Creates a texture based on data in compressed form.
  22189. *
  22190. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22191. *
  22192. * @augments Texture
  22193. */
  22194. class CompressedTexture extends Texture {
  22195. /**
  22196. * Constructs a new compressed texture.
  22197. *
  22198. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22199. * the data and dimensions.
  22200. * @param {number} width - The width of the texture.
  22201. * @param {number} height - The height of the texture.
  22202. * @param {number} [format=RGBAFormat] - The texture format.
  22203. * @param {number} [type=UnsignedByteType] - The texture type.
  22204. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22205. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22206. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22207. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22208. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22209. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22210. * @param {string} [colorSpace=NoColorSpace] - The color space.
  22211. */
  22212. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  22213. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  22214. /**
  22215. * This flag can be used for type testing.
  22216. *
  22217. * @type {boolean}
  22218. * @readonly
  22219. * @default true
  22220. */
  22221. this.isCompressedTexture = true;
  22222. /**
  22223. * The image property of a compressed texture just defines its dimensions.
  22224. *
  22225. * @type {{width:number,height:number}}
  22226. */
  22227. this.image = { width: width, height: height };
  22228. /**
  22229. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  22230. *
  22231. * @type {Array<Object>}
  22232. */
  22233. this.mipmaps = mipmaps;
  22234. /**
  22235. * If set to `true`, the texture is flipped along the vertical axis when
  22236. * uploaded to the GPU.
  22237. *
  22238. * Overwritten and set to `false` by default since it is not possible to
  22239. * flip compressed textures.
  22240. *
  22241. * @type {boolean}
  22242. * @default false
  22243. * @readonly
  22244. */
  22245. this.flipY = false;
  22246. /**
  22247. * Whether to generate mipmaps (if possible) for a texture.
  22248. *
  22249. * Overwritten and set to `false` by default since it is not
  22250. * possible to generate mipmaps for compressed data. Mipmaps
  22251. * must be embedded in the compressed texture file.
  22252. *
  22253. * @type {boolean}
  22254. * @default false
  22255. * @readonly
  22256. */
  22257. this.generateMipmaps = false;
  22258. }
  22259. }
  22260. /**
  22261. * Creates a texture 2D array based on data in compressed form.
  22262. *
  22263. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22264. *
  22265. * @augments CompressedTexture
  22266. */
  22267. class CompressedArrayTexture extends CompressedTexture {
  22268. /**
  22269. * Constructs a new compressed array texture.
  22270. *
  22271. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22272. * the data and dimensions.
  22273. * @param {number} width - The width of the texture.
  22274. * @param {number} height - The height of the texture.
  22275. * @param {number} depth - The depth of the texture.
  22276. * @param {number} [format=RGBAFormat] - The min filter value.
  22277. * @param {number} [type=UnsignedByteType] - The min filter value.
  22278. */
  22279. constructor( mipmaps, width, height, depth, format, type ) {
  22280. super( mipmaps, width, height, format, type );
  22281. /**
  22282. * This flag can be used for type testing.
  22283. *
  22284. * @type {boolean}
  22285. * @readonly
  22286. * @default true
  22287. */
  22288. this.isCompressedArrayTexture = true;
  22289. /**
  22290. * The image property of a compressed texture just defines its dimensions.
  22291. *
  22292. * @name CompressedArrayTexture#image
  22293. * @type {{width:number,height:number,depth:number}}
  22294. */
  22295. this.image.depth = depth;
  22296. /**
  22297. * This defines how the texture is wrapped in the depth and corresponds to
  22298. * *W* in UVW mapping.
  22299. *
  22300. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  22301. * @default ClampToEdgeWrapping
  22302. */
  22303. this.wrapR = ClampToEdgeWrapping;
  22304. /**
  22305. * A set of all layers which need to be updated in the texture.
  22306. *
  22307. * @type {Set<number>}
  22308. */
  22309. this.layerUpdates = new Set();
  22310. }
  22311. /**
  22312. * Describes that a specific layer of the texture needs to be updated.
  22313. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  22314. * entire compressed texture array is sent to the GPU. Marking specific
  22315. * layers will only transmit subsets of all mipmaps associated with a
  22316. * specific depth in the array which is often much more performant.
  22317. *
  22318. * @param {number} layerIndex - The layer index that should be updated.
  22319. */
  22320. addLayerUpdate( layerIndex ) {
  22321. this.layerUpdates.add( layerIndex );
  22322. }
  22323. /**
  22324. * Resets the layer updates registry.
  22325. */
  22326. clearLayerUpdates() {
  22327. this.layerUpdates.clear();
  22328. }
  22329. }
  22330. /**
  22331. * Creates a cube texture based on data in compressed form.
  22332. *
  22333. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22334. *
  22335. * @augments CompressedTexture
  22336. */
  22337. class CompressedCubeTexture extends CompressedTexture {
  22338. /**
  22339. * Constructs a new compressed texture.
  22340. *
  22341. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  22342. * @param {number} [format=RGBAFormat] - The texture format.
  22343. * @param {number} [type=UnsignedByteType] - The texture type.
  22344. */
  22345. constructor( images, format, type ) {
  22346. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  22347. /**
  22348. * This flag can be used for type testing.
  22349. *
  22350. * @type {boolean}
  22351. * @readonly
  22352. * @default true
  22353. */
  22354. this.isCompressedCubeTexture = true;
  22355. /**
  22356. * This flag can be used for type testing.
  22357. *
  22358. * @type {boolean}
  22359. * @readonly
  22360. * @default true
  22361. */
  22362. this.isCubeTexture = true;
  22363. this.image = images;
  22364. }
  22365. }
  22366. /**
  22367. * Creates a texture from a canvas element.
  22368. *
  22369. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22370. * to `true` immediately since a canvas can directly be used for rendering.
  22371. *
  22372. * @augments Texture
  22373. */
  22374. class CanvasTexture extends Texture {
  22375. /**
  22376. * Constructs a new texture.
  22377. *
  22378. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22379. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22380. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22381. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22382. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22383. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22384. * @param {number} [format=RGBAFormat] - The texture format.
  22385. * @param {number} [type=UnsignedByteType] - The texture type.
  22386. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22387. */
  22388. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22389. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22390. /**
  22391. * This flag can be used for type testing.
  22392. *
  22393. * @type {boolean}
  22394. * @readonly
  22395. * @default true
  22396. */
  22397. this.isCanvasTexture = true;
  22398. this.needsUpdate = true;
  22399. }
  22400. }
  22401. /**
  22402. * This class can be used to automatically save the depth information of a
  22403. * rendering into a texture.
  22404. *
  22405. * @augments Texture
  22406. */
  22407. class DepthTexture extends Texture {
  22408. /**
  22409. * Constructs a new depth texture.
  22410. *
  22411. * @param {number} width - The width of the texture.
  22412. * @param {number} height - The height of the texture.
  22413. * @param {number} [type=UnsignedIntType] - The texture type.
  22414. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22415. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22416. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22417. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22418. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22419. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22420. * @param {number} [format=DepthFormat] - The texture format.
  22421. * @param {number} [depth=1] - The depth of the texture.
  22422. */
  22423. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22424. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22425. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22426. }
  22427. const image = { width: width, height: height, depth: depth };
  22428. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22429. /**
  22430. * This flag can be used for type testing.
  22431. *
  22432. * @type {boolean}
  22433. * @readonly
  22434. * @default true
  22435. */
  22436. this.isDepthTexture = true;
  22437. /**
  22438. * If set to `true`, the texture is flipped along the vertical axis when
  22439. * uploaded to the GPU.
  22440. *
  22441. * Overwritten and set to `false` by default.
  22442. *
  22443. * @type {boolean}
  22444. * @default false
  22445. */
  22446. this.flipY = false;
  22447. /**
  22448. * Whether to generate mipmaps (if possible) for a texture.
  22449. *
  22450. * Overwritten and set to `false` by default.
  22451. *
  22452. * @type {boolean}
  22453. * @default false
  22454. */
  22455. this.generateMipmaps = false;
  22456. /**
  22457. * Code corresponding to the depth compare function.
  22458. *
  22459. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22460. * @default null
  22461. */
  22462. this.compareFunction = null;
  22463. }
  22464. copy( source ) {
  22465. super.copy( source );
  22466. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22467. this.compareFunction = source.compareFunction;
  22468. return this;
  22469. }
  22470. toJSON( meta ) {
  22471. const data = super.toJSON( meta );
  22472. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22473. return data;
  22474. }
  22475. }
  22476. /**
  22477. * This class can be used to automatically save the depth information of a
  22478. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  22479. *
  22480. * @augments DepthTexture
  22481. */
  22482. class CubeDepthTexture extends DepthTexture {
  22483. /**
  22484. * Constructs a new cube depth texture.
  22485. *
  22486. * @param {number} size - The size (width and height) of each cube face.
  22487. * @param {number} [type=UnsignedIntType] - The texture type.
  22488. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  22489. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22490. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22491. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  22492. * @param {number} [minFilter=NearestFilter] - The min filter value.
  22493. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22494. * @param {number} [format=DepthFormat] - The texture format.
  22495. */
  22496. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  22497. // Create 6 identical image descriptors for the cube faces
  22498. const image = { width: size, height: size, depth: 1 };
  22499. const images = [ image, image, image, image, image, image ];
  22500. // Call DepthTexture constructor with width, height
  22501. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  22502. // Replace the single image with the array of 6 images
  22503. this.image = images;
  22504. /**
  22505. * This flag can be used for type testing.
  22506. *
  22507. * @type {boolean}
  22508. * @readonly
  22509. * @default true
  22510. */
  22511. this.isCubeDepthTexture = true;
  22512. /**
  22513. * Set to true for cube texture handling in WebGLTextures.
  22514. *
  22515. * @type {boolean}
  22516. * @readonly
  22517. * @default true
  22518. */
  22519. this.isCubeTexture = true;
  22520. }
  22521. /**
  22522. * Alias for {@link CubeDepthTexture#image}.
  22523. *
  22524. * @type {Array<Image>}
  22525. */
  22526. get images() {
  22527. return this.image;
  22528. }
  22529. set images( value ) {
  22530. this.image = value;
  22531. }
  22532. }
  22533. /**
  22534. * Represents a texture created externally with the same renderer context.
  22535. *
  22536. * This may be a texture from a protected media stream, device camera feed,
  22537. * or other data feeds like a depth sensor.
  22538. *
  22539. * Note that this class is only supported in {@link WebGLRenderer}, and in
  22540. * the {@link WebGPURenderer} WebGPU backend.
  22541. *
  22542. * @augments Texture
  22543. */
  22544. class ExternalTexture extends Texture {
  22545. /**
  22546. * Creates a new raw texture.
  22547. *
  22548. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  22549. */
  22550. constructor( sourceTexture = null ) {
  22551. super();
  22552. /**
  22553. * The external source texture.
  22554. *
  22555. * @type {?(WebGLTexture|GPUTexture)}
  22556. * @default null
  22557. */
  22558. this.sourceTexture = sourceTexture;
  22559. /**
  22560. * This flag can be used for type testing.
  22561. *
  22562. * @type {boolean}
  22563. * @readonly
  22564. * @default true
  22565. */
  22566. this.isExternalTexture = true;
  22567. }
  22568. copy( source ) {
  22569. super.copy( source );
  22570. this.sourceTexture = source.sourceTexture;
  22571. return this;
  22572. }
  22573. }
  22574. /**
  22575. * A geometry class for representing a capsule.
  22576. *
  22577. * ```js
  22578. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22579. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22580. * const capsule = new THREE.Mesh( geometry, material );
  22581. * scene.add( capsule );
  22582. * ```
  22583. *
  22584. * @augments BufferGeometry
  22585. * @demo scenes/geometry-browser.html#CapsuleGeometry
  22586. */
  22587. class CapsuleGeometry extends BufferGeometry {
  22588. /**
  22589. * Constructs a new capsule geometry.
  22590. *
  22591. * @param {number} [radius=1] - Radius of the capsule.
  22592. * @param {number} [height=1] - Height of the middle section.
  22593. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22594. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22595. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22596. */
  22597. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22598. super();
  22599. this.type = 'CapsuleGeometry';
  22600. /**
  22601. * Holds the constructor parameters that have been
  22602. * used to generate the geometry. Any modification
  22603. * after instantiation does not change the geometry.
  22604. *
  22605. * @type {Object}
  22606. */
  22607. this.parameters = {
  22608. radius: radius,
  22609. height: height,
  22610. capSegments: capSegments,
  22611. radialSegments: radialSegments,
  22612. heightSegments: heightSegments,
  22613. };
  22614. height = Math.max( 0, height );
  22615. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22616. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22617. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22618. // buffers
  22619. const indices = [];
  22620. const vertices = [];
  22621. const normals = [];
  22622. const uvs = [];
  22623. // helper variables
  22624. const halfHeight = height / 2;
  22625. const capArcLength = ( Math.PI / 2 ) * radius;
  22626. const cylinderPartLength = height;
  22627. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22628. const numVerticalSegments = capSegments * 2 + heightSegments;
  22629. const verticesPerRow = radialSegments + 1;
  22630. const normal = new Vector3();
  22631. const vertex = new Vector3();
  22632. // generate vertices, normals, and uvs
  22633. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22634. let currentArcLength = 0;
  22635. let profileY = 0;
  22636. let profileRadius = 0;
  22637. let normalYComponent = 0;
  22638. if ( iy <= capSegments ) {
  22639. // bottom cap
  22640. const segmentProgress = iy / capSegments;
  22641. const angle = ( segmentProgress * Math.PI ) / 2;
  22642. profileY = - halfHeight - radius * Math.cos( angle );
  22643. profileRadius = radius * Math.sin( angle );
  22644. normalYComponent = - radius * Math.cos( angle );
  22645. currentArcLength = segmentProgress * capArcLength;
  22646. } else if ( iy <= capSegments + heightSegments ) {
  22647. // middle section
  22648. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22649. profileY = - halfHeight + segmentProgress * height;
  22650. profileRadius = radius;
  22651. normalYComponent = 0;
  22652. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22653. } else {
  22654. // top cap
  22655. const segmentProgress =
  22656. ( iy - capSegments - heightSegments ) / capSegments;
  22657. const angle = ( segmentProgress * Math.PI ) / 2;
  22658. profileY = halfHeight + radius * Math.sin( angle );
  22659. profileRadius = radius * Math.cos( angle );
  22660. normalYComponent = radius * Math.sin( angle );
  22661. currentArcLength =
  22662. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22663. }
  22664. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22665. // special case for the poles
  22666. let uOffset = 0;
  22667. if ( iy === 0 ) {
  22668. uOffset = 0.5 / radialSegments;
  22669. } else if ( iy === numVerticalSegments ) {
  22670. uOffset = -0.5 / radialSegments;
  22671. }
  22672. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22673. const u = ix / radialSegments;
  22674. const theta = u * Math.PI * 2;
  22675. const sinTheta = Math.sin( theta );
  22676. const cosTheta = Math.cos( theta );
  22677. // vertex
  22678. vertex.x = - profileRadius * cosTheta;
  22679. vertex.y = profileY;
  22680. vertex.z = profileRadius * sinTheta;
  22681. vertices.push( vertex.x, vertex.y, vertex.z );
  22682. // normal
  22683. normal.set(
  22684. - profileRadius * cosTheta,
  22685. normalYComponent,
  22686. profileRadius * sinTheta
  22687. );
  22688. normal.normalize();
  22689. normals.push( normal.x, normal.y, normal.z );
  22690. // uv
  22691. uvs.push( u + uOffset, v );
  22692. }
  22693. if ( iy > 0 ) {
  22694. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22695. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22696. const i1 = prevIndexRow + ix;
  22697. const i2 = prevIndexRow + ix + 1;
  22698. const i3 = iy * verticesPerRow + ix;
  22699. const i4 = iy * verticesPerRow + ix + 1;
  22700. indices.push( i1, i2, i3 );
  22701. indices.push( i2, i4, i3 );
  22702. }
  22703. }
  22704. }
  22705. // build geometry
  22706. this.setIndex( indices );
  22707. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22708. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22709. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22710. }
  22711. copy( source ) {
  22712. super.copy( source );
  22713. this.parameters = Object.assign( {}, source.parameters );
  22714. return this;
  22715. }
  22716. /**
  22717. * Factory method for creating an instance of this class from the given
  22718. * JSON object.
  22719. *
  22720. * @param {Object} data - A JSON object representing the serialized geometry.
  22721. * @return {CapsuleGeometry} A new instance.
  22722. */
  22723. static fromJSON( data ) {
  22724. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22725. }
  22726. }
  22727. /**
  22728. * A simple shape of Euclidean geometry. It is constructed from a
  22729. * number of triangular segments that are oriented around a central point and
  22730. * extend as far out as a given radius. It is built counter-clockwise from a
  22731. * start angle and a given central angle. It can also be used to create
  22732. * regular polygons, where the number of segments determines the number of
  22733. * sides.
  22734. *
  22735. * ```js
  22736. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22737. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22738. * const circle = new THREE.Mesh( geometry, material );
  22739. * scene.add( circle )
  22740. * ```
  22741. *
  22742. * @augments BufferGeometry
  22743. * @demo scenes/geometry-browser.html#CircleGeometry
  22744. */
  22745. class CircleGeometry extends BufferGeometry {
  22746. /**
  22747. * Constructs a new circle geometry.
  22748. *
  22749. * @param {number} [radius=1] - Radius of the circle.
  22750. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22751. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22752. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22753. * of the circular sector in radians. The default value results in a complete circle.
  22754. */
  22755. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22756. super();
  22757. this.type = 'CircleGeometry';
  22758. /**
  22759. * Holds the constructor parameters that have been
  22760. * used to generate the geometry. Any modification
  22761. * after instantiation does not change the geometry.
  22762. *
  22763. * @type {Object}
  22764. */
  22765. this.parameters = {
  22766. radius: radius,
  22767. segments: segments,
  22768. thetaStart: thetaStart,
  22769. thetaLength: thetaLength
  22770. };
  22771. segments = Math.max( 3, segments );
  22772. // buffers
  22773. const indices = [];
  22774. const vertices = [];
  22775. const normals = [];
  22776. const uvs = [];
  22777. // helper variables
  22778. const vertex = new Vector3();
  22779. const uv = new Vector2();
  22780. // center point
  22781. vertices.push( 0, 0, 0 );
  22782. normals.push( 0, 0, 1 );
  22783. uvs.push( 0.5, 0.5 );
  22784. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22785. const segment = thetaStart + s / segments * thetaLength;
  22786. // vertex
  22787. vertex.x = radius * Math.cos( segment );
  22788. vertex.y = radius * Math.sin( segment );
  22789. vertices.push( vertex.x, vertex.y, vertex.z );
  22790. // normal
  22791. normals.push( 0, 0, 1 );
  22792. // uvs
  22793. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22794. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22795. uvs.push( uv.x, uv.y );
  22796. }
  22797. // indices
  22798. for ( let i = 1; i <= segments; i ++ ) {
  22799. indices.push( i, i + 1, 0 );
  22800. }
  22801. // build geometry
  22802. this.setIndex( indices );
  22803. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22804. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22805. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22806. }
  22807. copy( source ) {
  22808. super.copy( source );
  22809. this.parameters = Object.assign( {}, source.parameters );
  22810. return this;
  22811. }
  22812. /**
  22813. * Factory method for creating an instance of this class from the given
  22814. * JSON object.
  22815. *
  22816. * @param {Object} data - A JSON object representing the serialized geometry.
  22817. * @return {CircleGeometry} A new instance.
  22818. */
  22819. static fromJSON( data ) {
  22820. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22821. }
  22822. }
  22823. /**
  22824. * A geometry class for representing a cylinder.
  22825. *
  22826. * ```js
  22827. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22828. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22829. * const cylinder = new THREE.Mesh( geometry, material );
  22830. * scene.add( cylinder );
  22831. * ```
  22832. *
  22833. * @augments BufferGeometry
  22834. * @demo scenes/geometry-browser.html#CylinderGeometry
  22835. */
  22836. class CylinderGeometry extends BufferGeometry {
  22837. /**
  22838. * Constructs a new cylinder geometry.
  22839. *
  22840. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22841. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22842. * @param {number} [height=1] - Height of the cylinder.
  22843. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22844. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22845. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22846. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22847. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22848. * The default value results in a complete cylinder.
  22849. */
  22850. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22851. super();
  22852. this.type = 'CylinderGeometry';
  22853. /**
  22854. * Holds the constructor parameters that have been
  22855. * used to generate the geometry. Any modification
  22856. * after instantiation does not change the geometry.
  22857. *
  22858. * @type {Object}
  22859. */
  22860. this.parameters = {
  22861. radiusTop: radiusTop,
  22862. radiusBottom: radiusBottom,
  22863. height: height,
  22864. radialSegments: radialSegments,
  22865. heightSegments: heightSegments,
  22866. openEnded: openEnded,
  22867. thetaStart: thetaStart,
  22868. thetaLength: thetaLength
  22869. };
  22870. const scope = this;
  22871. radialSegments = Math.floor( radialSegments );
  22872. heightSegments = Math.floor( heightSegments );
  22873. // buffers
  22874. const indices = [];
  22875. const vertices = [];
  22876. const normals = [];
  22877. const uvs = [];
  22878. // helper variables
  22879. let index = 0;
  22880. const indexArray = [];
  22881. const halfHeight = height / 2;
  22882. let groupStart = 0;
  22883. // generate geometry
  22884. generateTorso();
  22885. if ( openEnded === false ) {
  22886. if ( radiusTop > 0 ) generateCap( true );
  22887. if ( radiusBottom > 0 ) generateCap( false );
  22888. }
  22889. // build geometry
  22890. this.setIndex( indices );
  22891. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22892. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22893. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22894. function generateTorso() {
  22895. const normal = new Vector3();
  22896. const vertex = new Vector3();
  22897. let groupCount = 0;
  22898. // this will be used to calculate the normal
  22899. const slope = ( radiusBottom - radiusTop ) / height;
  22900. // generate vertices, normals and uvs
  22901. for ( let y = 0; y <= heightSegments; y ++ ) {
  22902. const indexRow = [];
  22903. const v = y / heightSegments;
  22904. // calculate the radius of the current row
  22905. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22906. for ( let x = 0; x <= radialSegments; x ++ ) {
  22907. const u = x / radialSegments;
  22908. const theta = u * thetaLength + thetaStart;
  22909. const sinTheta = Math.sin( theta );
  22910. const cosTheta = Math.cos( theta );
  22911. // vertex
  22912. vertex.x = radius * sinTheta;
  22913. vertex.y = - v * height + halfHeight;
  22914. vertex.z = radius * cosTheta;
  22915. vertices.push( vertex.x, vertex.y, vertex.z );
  22916. // normal
  22917. normal.set( sinTheta, slope, cosTheta ).normalize();
  22918. normals.push( normal.x, normal.y, normal.z );
  22919. // uv
  22920. uvs.push( u, 1 - v );
  22921. // save index of vertex in respective row
  22922. indexRow.push( index ++ );
  22923. }
  22924. // now save vertices of the row in our index array
  22925. indexArray.push( indexRow );
  22926. }
  22927. // generate indices
  22928. for ( let x = 0; x < radialSegments; x ++ ) {
  22929. for ( let y = 0; y < heightSegments; y ++ ) {
  22930. // we use the index array to access the correct indices
  22931. const a = indexArray[ y ][ x ];
  22932. const b = indexArray[ y + 1 ][ x ];
  22933. const c = indexArray[ y + 1 ][ x + 1 ];
  22934. const d = indexArray[ y ][ x + 1 ];
  22935. // faces
  22936. if ( radiusTop > 0 || y !== 0 ) {
  22937. indices.push( a, b, d );
  22938. groupCount += 3;
  22939. }
  22940. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22941. indices.push( b, c, d );
  22942. groupCount += 3;
  22943. }
  22944. }
  22945. }
  22946. // add a group to the geometry. this will ensure multi material support
  22947. scope.addGroup( groupStart, groupCount, 0 );
  22948. // calculate new start value for groups
  22949. groupStart += groupCount;
  22950. }
  22951. function generateCap( top ) {
  22952. // save the index of the first center vertex
  22953. const centerIndexStart = index;
  22954. const uv = new Vector2();
  22955. const vertex = new Vector3();
  22956. let groupCount = 0;
  22957. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22958. const sign = ( top === true ) ? 1 : -1;
  22959. // first we generate the center vertex data of the cap.
  22960. // because the geometry needs one set of uvs per face,
  22961. // we must generate a center vertex per face/segment
  22962. for ( let x = 1; x <= radialSegments; x ++ ) {
  22963. // vertex
  22964. vertices.push( 0, halfHeight * sign, 0 );
  22965. // normal
  22966. normals.push( 0, sign, 0 );
  22967. // uv
  22968. uvs.push( 0.5, 0.5 );
  22969. // increase index
  22970. index ++;
  22971. }
  22972. // save the index of the last center vertex
  22973. const centerIndexEnd = index;
  22974. // now we generate the surrounding vertices, normals and uvs
  22975. for ( let x = 0; x <= radialSegments; x ++ ) {
  22976. const u = x / radialSegments;
  22977. const theta = u * thetaLength + thetaStart;
  22978. const cosTheta = Math.cos( theta );
  22979. const sinTheta = Math.sin( theta );
  22980. // vertex
  22981. vertex.x = radius * sinTheta;
  22982. vertex.y = halfHeight * sign;
  22983. vertex.z = radius * cosTheta;
  22984. vertices.push( vertex.x, vertex.y, vertex.z );
  22985. // normal
  22986. normals.push( 0, sign, 0 );
  22987. // uv
  22988. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22989. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22990. uvs.push( uv.x, uv.y );
  22991. // increase index
  22992. index ++;
  22993. }
  22994. // generate indices
  22995. for ( let x = 0; x < radialSegments; x ++ ) {
  22996. const c = centerIndexStart + x;
  22997. const i = centerIndexEnd + x;
  22998. if ( top === true ) {
  22999. // face top
  23000. indices.push( i, i + 1, c );
  23001. } else {
  23002. // face bottom
  23003. indices.push( i + 1, i, c );
  23004. }
  23005. groupCount += 3;
  23006. }
  23007. // add a group to the geometry. this will ensure multi material support
  23008. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  23009. // calculate new start value for groups
  23010. groupStart += groupCount;
  23011. }
  23012. }
  23013. copy( source ) {
  23014. super.copy( source );
  23015. this.parameters = Object.assign( {}, source.parameters );
  23016. return this;
  23017. }
  23018. /**
  23019. * Factory method for creating an instance of this class from the given
  23020. * JSON object.
  23021. *
  23022. * @param {Object} data - A JSON object representing the serialized geometry.
  23023. * @return {CylinderGeometry} A new instance.
  23024. */
  23025. static fromJSON( data ) {
  23026. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  23027. }
  23028. }
  23029. /**
  23030. * A geometry class for representing a cone.
  23031. *
  23032. * ```js
  23033. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  23034. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23035. * const cone = new THREE.Mesh(geometry, material );
  23036. * scene.add( cone );
  23037. * ```
  23038. *
  23039. * @augments CylinderGeometry
  23040. * @demo scenes/geometry-browser.html#ConeGeometry
  23041. */
  23042. class ConeGeometry extends CylinderGeometry {
  23043. /**
  23044. * Constructs a new cone geometry.
  23045. *
  23046. * @param {number} [radius=1] - Radius of the cone base.
  23047. * @param {number} [height=1] - Height of the cone.
  23048. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  23049. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  23050. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  23051. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  23052. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  23053. * The default value results in a complete cone.
  23054. */
  23055. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23056. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  23057. this.type = 'ConeGeometry';
  23058. /**
  23059. * Holds the constructor parameters that have been
  23060. * used to generate the geometry. Any modification
  23061. * after instantiation does not change the geometry.
  23062. *
  23063. * @type {Object}
  23064. */
  23065. this.parameters = {
  23066. radius: radius,
  23067. height: height,
  23068. radialSegments: radialSegments,
  23069. heightSegments: heightSegments,
  23070. openEnded: openEnded,
  23071. thetaStart: thetaStart,
  23072. thetaLength: thetaLength
  23073. };
  23074. }
  23075. /**
  23076. * Factory method for creating an instance of this class from the given
  23077. * JSON object.
  23078. *
  23079. * @param {Object} data - A JSON object representing the serialized geometry.
  23080. * @return {ConeGeometry} A new instance.
  23081. */
  23082. static fromJSON( data ) {
  23083. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  23084. }
  23085. }
  23086. /**
  23087. * A polyhedron is a solid in three dimensions with flat faces. This class
  23088. * will take an array of vertices, project them onto a sphere, and then
  23089. * divide them up to the desired level of detail.
  23090. *
  23091. * @augments BufferGeometry
  23092. */
  23093. class PolyhedronGeometry extends BufferGeometry {
  23094. /**
  23095. * Constructs a new polyhedron geometry.
  23096. *
  23097. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  23098. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  23099. * @param {number} [radius=1] - The radius of the shape.
  23100. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  23101. */
  23102. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  23103. super();
  23104. this.type = 'PolyhedronGeometry';
  23105. /**
  23106. * Holds the constructor parameters that have been
  23107. * used to generate the geometry. Any modification
  23108. * after instantiation does not change the geometry.
  23109. *
  23110. * @type {Object}
  23111. */
  23112. this.parameters = {
  23113. vertices: vertices,
  23114. indices: indices,
  23115. radius: radius,
  23116. detail: detail
  23117. };
  23118. // default buffer data
  23119. const vertexBuffer = [];
  23120. const uvBuffer = [];
  23121. // the subdivision creates the vertex buffer data
  23122. subdivide( detail );
  23123. // all vertices should lie on a conceptual sphere with a given radius
  23124. applyRadius( radius );
  23125. // finally, create the uv data
  23126. generateUVs();
  23127. // build non-indexed geometry
  23128. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  23129. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  23130. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  23131. if ( detail === 0 ) {
  23132. this.computeVertexNormals(); // flat normals
  23133. } else {
  23134. this.normalizeNormals(); // smooth normals
  23135. }
  23136. // helper functions
  23137. function subdivide( detail ) {
  23138. const a = new Vector3();
  23139. const b = new Vector3();
  23140. const c = new Vector3();
  23141. // iterate over all faces and apply a subdivision with the given detail value
  23142. for ( let i = 0; i < indices.length; i += 3 ) {
  23143. // get the vertices of the face
  23144. getVertexByIndex( indices[ i + 0 ], a );
  23145. getVertexByIndex( indices[ i + 1 ], b );
  23146. getVertexByIndex( indices[ i + 2 ], c );
  23147. // perform subdivision
  23148. subdivideFace( a, b, c, detail );
  23149. }
  23150. }
  23151. function subdivideFace( a, b, c, detail ) {
  23152. const cols = detail + 1;
  23153. // we use this multidimensional array as a data structure for creating the subdivision
  23154. const v = [];
  23155. // construct all of the vertices for this subdivision
  23156. for ( let i = 0; i <= cols; i ++ ) {
  23157. v[ i ] = [];
  23158. const aj = a.clone().lerp( c, i / cols );
  23159. const bj = b.clone().lerp( c, i / cols );
  23160. const rows = cols - i;
  23161. for ( let j = 0; j <= rows; j ++ ) {
  23162. if ( j === 0 && i === cols ) {
  23163. v[ i ][ j ] = aj;
  23164. } else {
  23165. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  23166. }
  23167. }
  23168. }
  23169. // construct all of the faces
  23170. for ( let i = 0; i < cols; i ++ ) {
  23171. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  23172. const k = Math.floor( j / 2 );
  23173. if ( j % 2 === 0 ) {
  23174. pushVertex( v[ i ][ k + 1 ] );
  23175. pushVertex( v[ i + 1 ][ k ] );
  23176. pushVertex( v[ i ][ k ] );
  23177. } else {
  23178. pushVertex( v[ i ][ k + 1 ] );
  23179. pushVertex( v[ i + 1 ][ k + 1 ] );
  23180. pushVertex( v[ i + 1 ][ k ] );
  23181. }
  23182. }
  23183. }
  23184. }
  23185. function applyRadius( radius ) {
  23186. const vertex = new Vector3();
  23187. // iterate over the entire buffer and apply the radius to each vertex
  23188. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  23189. vertex.x = vertexBuffer[ i + 0 ];
  23190. vertex.y = vertexBuffer[ i + 1 ];
  23191. vertex.z = vertexBuffer[ i + 2 ];
  23192. vertex.normalize().multiplyScalar( radius );
  23193. vertexBuffer[ i + 0 ] = vertex.x;
  23194. vertexBuffer[ i + 1 ] = vertex.y;
  23195. vertexBuffer[ i + 2 ] = vertex.z;
  23196. }
  23197. }
  23198. function generateUVs() {
  23199. const vertex = new Vector3();
  23200. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  23201. vertex.x = vertexBuffer[ i + 0 ];
  23202. vertex.y = vertexBuffer[ i + 1 ];
  23203. vertex.z = vertexBuffer[ i + 2 ];
  23204. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  23205. const v = inclination( vertex ) / Math.PI + 0.5;
  23206. uvBuffer.push( u, 1 - v );
  23207. }
  23208. correctUVs();
  23209. correctSeam();
  23210. }
  23211. function correctSeam() {
  23212. // handle case when face straddles the seam, see #3269
  23213. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  23214. // uv data of a single face
  23215. const x0 = uvBuffer[ i + 0 ];
  23216. const x1 = uvBuffer[ i + 2 ];
  23217. const x2 = uvBuffer[ i + 4 ];
  23218. const max = Math.max( x0, x1, x2 );
  23219. const min = Math.min( x0, x1, x2 );
  23220. // 0.9 is somewhat arbitrary
  23221. if ( max > 0.9 && min < 0.1 ) {
  23222. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  23223. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  23224. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  23225. }
  23226. }
  23227. }
  23228. function pushVertex( vertex ) {
  23229. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  23230. }
  23231. function getVertexByIndex( index, vertex ) {
  23232. const stride = index * 3;
  23233. vertex.x = vertices[ stride + 0 ];
  23234. vertex.y = vertices[ stride + 1 ];
  23235. vertex.z = vertices[ stride + 2 ];
  23236. }
  23237. function correctUVs() {
  23238. const a = new Vector3();
  23239. const b = new Vector3();
  23240. const c = new Vector3();
  23241. const centroid = new Vector3();
  23242. const uvA = new Vector2();
  23243. const uvB = new Vector2();
  23244. const uvC = new Vector2();
  23245. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  23246. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  23247. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  23248. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  23249. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  23250. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  23251. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  23252. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  23253. const azi = azimuth( centroid );
  23254. correctUV( uvA, j + 0, a, azi );
  23255. correctUV( uvB, j + 2, b, azi );
  23256. correctUV( uvC, j + 4, c, azi );
  23257. }
  23258. }
  23259. function correctUV( uv, stride, vector, azimuth ) {
  23260. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  23261. uvBuffer[ stride ] = uv.x - 1;
  23262. }
  23263. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  23264. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  23265. }
  23266. }
  23267. // Angle around the Y axis, counter-clockwise when looking from above.
  23268. function azimuth( vector ) {
  23269. return Math.atan2( vector.z, - vector.x );
  23270. }
  23271. // Angle above the XZ plane.
  23272. function inclination( vector ) {
  23273. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23274. }
  23275. }
  23276. copy( source ) {
  23277. super.copy( source );
  23278. this.parameters = Object.assign( {}, source.parameters );
  23279. return this;
  23280. }
  23281. /**
  23282. * Factory method for creating an instance of this class from the given
  23283. * JSON object.
  23284. *
  23285. * @param {Object} data - A JSON object representing the serialized geometry.
  23286. * @return {PolyhedronGeometry} A new instance.
  23287. */
  23288. static fromJSON( data ) {
  23289. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  23290. }
  23291. }
  23292. /**
  23293. * A geometry class for representing a dodecahedron.
  23294. *
  23295. * ```js
  23296. * const geometry = new THREE.DodecahedronGeometry();
  23297. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23298. * const dodecahedron = new THREE.Mesh( geometry, material );
  23299. * scene.add( dodecahedron );
  23300. * ```
  23301. *
  23302. * @augments PolyhedronGeometry
  23303. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  23304. */
  23305. class DodecahedronGeometry extends PolyhedronGeometry {
  23306. /**
  23307. * Constructs a new dodecahedron geometry.
  23308. *
  23309. * @param {number} [radius=1] - Radius of the dodecahedron.
  23310. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  23311. */
  23312. constructor( radius = 1, detail = 0 ) {
  23313. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23314. const r = 1 / t;
  23315. const vertices = [
  23316. // (±1, ±1, ±1)
  23317. -1, -1, -1, -1, -1, 1,
  23318. -1, 1, -1, -1, 1, 1,
  23319. 1, -1, -1, 1, -1, 1,
  23320. 1, 1, -1, 1, 1, 1,
  23321. // (0, ±1/φ, ±φ)
  23322. 0, - r, - t, 0, - r, t,
  23323. 0, r, - t, 0, r, t,
  23324. // (±1/φ, ±φ, 0)
  23325. - r, - t, 0, - r, t, 0,
  23326. r, - t, 0, r, t, 0,
  23327. // (±φ, 0, ±1/φ)
  23328. - t, 0, - r, t, 0, - r,
  23329. - t, 0, r, t, 0, r
  23330. ];
  23331. const indices = [
  23332. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23333. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23334. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23335. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23336. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23337. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23338. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23339. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23340. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23341. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23342. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23343. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23344. ];
  23345. super( vertices, indices, radius, detail );
  23346. this.type = 'DodecahedronGeometry';
  23347. /**
  23348. * Holds the constructor parameters that have been
  23349. * used to generate the geometry. Any modification
  23350. * after instantiation does not change the geometry.
  23351. *
  23352. * @type {Object}
  23353. */
  23354. this.parameters = {
  23355. radius: radius,
  23356. detail: detail
  23357. };
  23358. }
  23359. /**
  23360. * Factory method for creating an instance of this class from the given
  23361. * JSON object.
  23362. *
  23363. * @param {Object} data - A JSON object representing the serialized geometry.
  23364. * @return {DodecahedronGeometry} A new instance.
  23365. */
  23366. static fromJSON( data ) {
  23367. return new DodecahedronGeometry( data.radius, data.detail );
  23368. }
  23369. }
  23370. const _v0 = /*@__PURE__*/ new Vector3();
  23371. const _v1$1 = /*@__PURE__*/ new Vector3();
  23372. const _normal = /*@__PURE__*/ new Vector3();
  23373. const _triangle = /*@__PURE__*/ new Triangle();
  23374. /**
  23375. * Can be used as a helper object to view the edges of a geometry.
  23376. *
  23377. * ```js
  23378. * const geometry = new THREE.BoxGeometry();
  23379. * const edges = new THREE.EdgesGeometry( geometry );
  23380. * const line = new THREE.LineSegments( edges );
  23381. * scene.add( line );
  23382. * ```
  23383. *
  23384. * Note: It is not yet possible to serialize/deserialize instances of this class.
  23385. *
  23386. * @augments BufferGeometry
  23387. */
  23388. class EdgesGeometry extends BufferGeometry {
  23389. /**
  23390. * Constructs a new edges geometry.
  23391. *
  23392. * @param {?BufferGeometry} [geometry=null] - The geometry.
  23393. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  23394. * between the face normals of the adjoining faces exceeds this value.
  23395. */
  23396. constructor( geometry = null, thresholdAngle = 1 ) {
  23397. super();
  23398. this.type = 'EdgesGeometry';
  23399. /**
  23400. * Holds the constructor parameters that have been
  23401. * used to generate the geometry. Any modification
  23402. * after instantiation does not change the geometry.
  23403. *
  23404. * @type {Object}
  23405. */
  23406. this.parameters = {
  23407. geometry: geometry,
  23408. thresholdAngle: thresholdAngle
  23409. };
  23410. if ( geometry !== null ) {
  23411. const precisionPoints = 4;
  23412. const precision = Math.pow( 10, precisionPoints );
  23413. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  23414. const indexAttr = geometry.getIndex();
  23415. const positionAttr = geometry.getAttribute( 'position' );
  23416. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23417. const indexArr = [ 0, 0, 0 ];
  23418. const vertKeys = [ 'a', 'b', 'c' ];
  23419. const hashes = new Array( 3 );
  23420. const edgeData = {};
  23421. const vertices = [];
  23422. for ( let i = 0; i < indexCount; i += 3 ) {
  23423. if ( indexAttr ) {
  23424. indexArr[ 0 ] = indexAttr.getX( i );
  23425. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  23426. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  23427. } else {
  23428. indexArr[ 0 ] = i;
  23429. indexArr[ 1 ] = i + 1;
  23430. indexArr[ 2 ] = i + 2;
  23431. }
  23432. const { a, b, c } = _triangle;
  23433. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  23434. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  23435. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  23436. _triangle.getNormal( _normal );
  23437. // create hashes for the edge from the vertices
  23438. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  23439. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  23440. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  23441. // skip degenerate triangles
  23442. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  23443. continue;
  23444. }
  23445. // iterate over every edge
  23446. for ( let j = 0; j < 3; j ++ ) {
  23447. // get the first and next vertex making up the edge
  23448. const jNext = ( j + 1 ) % 3;
  23449. const vecHash0 = hashes[ j ];
  23450. const vecHash1 = hashes[ jNext ];
  23451. const v0 = _triangle[ vertKeys[ j ] ];
  23452. const v1 = _triangle[ vertKeys[ jNext ] ];
  23453. const hash = `${ vecHash0 }_${ vecHash1 }`;
  23454. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  23455. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  23456. // if we found a sibling edge add it into the vertex array if
  23457. // it meets the angle threshold and delete the edge from the map.
  23458. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  23459. vertices.push( v0.x, v0.y, v0.z );
  23460. vertices.push( v1.x, v1.y, v1.z );
  23461. }
  23462. edgeData[ reverseHash ] = null;
  23463. } else if ( ! ( hash in edgeData ) ) {
  23464. // if we've already got an edge here then skip adding a new one
  23465. edgeData[ hash ] = {
  23466. index0: indexArr[ j ],
  23467. index1: indexArr[ jNext ],
  23468. normal: _normal.clone(),
  23469. };
  23470. }
  23471. }
  23472. }
  23473. // iterate over all remaining, unmatched edges and add them to the vertex array
  23474. for ( const key in edgeData ) {
  23475. if ( edgeData[ key ] ) {
  23476. const { index0, index1 } = edgeData[ key ];
  23477. _v0.fromBufferAttribute( positionAttr, index0 );
  23478. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23479. vertices.push( _v0.x, _v0.y, _v0.z );
  23480. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23481. }
  23482. }
  23483. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23484. }
  23485. }
  23486. copy( source ) {
  23487. super.copy( source );
  23488. this.parameters = Object.assign( {}, source.parameters );
  23489. return this;
  23490. }
  23491. }
  23492. /**
  23493. * An abstract base class for creating an analytic curve object that contains methods
  23494. * for interpolation.
  23495. *
  23496. * @abstract
  23497. */
  23498. class Curve {
  23499. /**
  23500. * Constructs a new curve.
  23501. */
  23502. constructor() {
  23503. /**
  23504. * The type property is used for detecting the object type
  23505. * in context of serialization/deserialization.
  23506. *
  23507. * @type {string}
  23508. * @readonly
  23509. */
  23510. this.type = 'Curve';
  23511. /**
  23512. * This value determines the amount of divisions when calculating the
  23513. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23514. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23515. * recommended to increase the value of this property if the curve is very large.
  23516. *
  23517. * @type {number}
  23518. * @default 200
  23519. */
  23520. this.arcLengthDivisions = 200;
  23521. /**
  23522. * Must be set to `true` if the curve parameters have changed.
  23523. *
  23524. * @type {boolean}
  23525. * @default false
  23526. */
  23527. this.needsUpdate = false;
  23528. /**
  23529. * An internal cache that holds precomputed curve length values.
  23530. *
  23531. * @private
  23532. * @type {?Array<number>}
  23533. * @default null
  23534. */
  23535. this.cacheArcLengths = null;
  23536. }
  23537. /**
  23538. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23539. * for the given interpolation factor.
  23540. *
  23541. * @abstract
  23542. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23543. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23544. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23545. */
  23546. getPoint( /* t, optionalTarget */ ) {
  23547. warn( 'Curve: .getPoint() not implemented.' );
  23548. }
  23549. /**
  23550. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23551. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23552. * of the curve which equidistant samples.
  23553. *
  23554. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23555. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23556. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23557. */
  23558. getPointAt( u, optionalTarget ) {
  23559. const t = this.getUtoTmapping( u );
  23560. return this.getPoint( t, optionalTarget );
  23561. }
  23562. /**
  23563. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23564. * the curve shape.
  23565. *
  23566. * @param {number} [divisions=5] - The number of divisions.
  23567. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23568. */
  23569. getPoints( divisions = 5 ) {
  23570. const points = [];
  23571. for ( let d = 0; d <= divisions; d ++ ) {
  23572. points.push( this.getPoint( d / divisions ) );
  23573. }
  23574. return points;
  23575. }
  23576. // Get sequence of points using getPointAt( u )
  23577. /**
  23578. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23579. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23580. * curve.
  23581. *
  23582. * @param {number} [divisions=5] - The number of divisions.
  23583. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23584. */
  23585. getSpacedPoints( divisions = 5 ) {
  23586. const points = [];
  23587. for ( let d = 0; d <= divisions; d ++ ) {
  23588. points.push( this.getPointAt( d / divisions ) );
  23589. }
  23590. return points;
  23591. }
  23592. /**
  23593. * Returns the total arc length of the curve.
  23594. *
  23595. * @return {number} The length of the curve.
  23596. */
  23597. getLength() {
  23598. const lengths = this.getLengths();
  23599. return lengths[ lengths.length - 1 ];
  23600. }
  23601. /**
  23602. * Returns an array of cumulative segment lengths of the curve.
  23603. *
  23604. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23605. * @return {Array<number>} An array holding the cumulative segment lengths.
  23606. */
  23607. getLengths( divisions = this.arcLengthDivisions ) {
  23608. if ( this.cacheArcLengths &&
  23609. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23610. ! this.needsUpdate ) {
  23611. return this.cacheArcLengths;
  23612. }
  23613. this.needsUpdate = false;
  23614. const cache = [];
  23615. let current, last = this.getPoint( 0 );
  23616. let sum = 0;
  23617. cache.push( 0 );
  23618. for ( let p = 1; p <= divisions; p ++ ) {
  23619. current = this.getPoint( p / divisions );
  23620. sum += current.distanceTo( last );
  23621. cache.push( sum );
  23622. last = current;
  23623. }
  23624. this.cacheArcLengths = cache;
  23625. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23626. }
  23627. /**
  23628. * Update the cumulative segment distance cache. The method must be called
  23629. * every time curve parameters are changed. If an updated curve is part of a
  23630. * composed curve like {@link CurvePath}, this method must be called on the
  23631. * composed curve, too.
  23632. */
  23633. updateArcLengths() {
  23634. this.needsUpdate = true;
  23635. this.getLengths();
  23636. }
  23637. /**
  23638. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23639. * interpolation factor in the same range that can be ued to sample equidistant points
  23640. * from a curve.
  23641. *
  23642. * @param {number} u - The interpolation factor.
  23643. * @param {?number} distance - An optional distance on the curve.
  23644. * @return {number} The updated interpolation factor.
  23645. */
  23646. getUtoTmapping( u, distance = null ) {
  23647. const arcLengths = this.getLengths();
  23648. let i = 0;
  23649. const il = arcLengths.length;
  23650. let targetArcLength; // The targeted u distance value to get
  23651. if ( distance ) {
  23652. targetArcLength = distance;
  23653. } else {
  23654. targetArcLength = u * arcLengths[ il - 1 ];
  23655. }
  23656. // binary search for the index with largest value smaller than target u distance
  23657. let low = 0, high = il - 1, comparison;
  23658. while ( low <= high ) {
  23659. 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
  23660. comparison = arcLengths[ i ] - targetArcLength;
  23661. if ( comparison < 0 ) {
  23662. low = i + 1;
  23663. } else if ( comparison > 0 ) {
  23664. high = i - 1;
  23665. } else {
  23666. high = i;
  23667. break;
  23668. // DONE
  23669. }
  23670. }
  23671. i = high;
  23672. if ( arcLengths[ i ] === targetArcLength ) {
  23673. return i / ( il - 1 );
  23674. }
  23675. // we could get finer grain at lengths, or use simple interpolation between two points
  23676. const lengthBefore = arcLengths[ i ];
  23677. const lengthAfter = arcLengths[ i + 1 ];
  23678. const segmentLength = lengthAfter - lengthBefore;
  23679. // determine where we are between the 'before' and 'after' points
  23680. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23681. // add that fractional amount to t
  23682. const t = ( i + segmentFraction ) / ( il - 1 );
  23683. return t;
  23684. }
  23685. /**
  23686. * Returns a unit vector tangent for the given interpolation factor.
  23687. * If the derived curve does not implement its tangent derivation,
  23688. * two points a small delta apart will be used to find its gradient
  23689. * which seems to give a reasonable approximation.
  23690. *
  23691. * @param {number} t - The interpolation factor.
  23692. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23693. * @return {(Vector2|Vector3)} The tangent vector.
  23694. */
  23695. getTangent( t, optionalTarget ) {
  23696. const delta = 0.0001;
  23697. let t1 = t - delta;
  23698. let t2 = t + delta;
  23699. // Capping in case of danger
  23700. if ( t1 < 0 ) t1 = 0;
  23701. if ( t2 > 1 ) t2 = 1;
  23702. const pt1 = this.getPoint( t1 );
  23703. const pt2 = this.getPoint( t2 );
  23704. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23705. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23706. return tangent;
  23707. }
  23708. /**
  23709. * Same as {@link Curve#getTangent} but with equidistant samples.
  23710. *
  23711. * @param {number} u - The interpolation factor.
  23712. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23713. * @return {(Vector2|Vector3)} The tangent vector.
  23714. * @see {@link Curve#getPointAt}
  23715. */
  23716. getTangentAt( u, optionalTarget ) {
  23717. const t = this.getUtoTmapping( u );
  23718. return this.getTangent( t, optionalTarget );
  23719. }
  23720. /**
  23721. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23722. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23723. *
  23724. * @param {number} segments - The number of segments.
  23725. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23726. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23727. */
  23728. computeFrenetFrames( segments, closed = false ) {
  23729. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23730. const normal = new Vector3();
  23731. const tangents = [];
  23732. const normals = [];
  23733. const binormals = [];
  23734. const vec = new Vector3();
  23735. const mat = new Matrix4();
  23736. // compute the tangent vectors for each segment on the curve
  23737. for ( let i = 0; i <= segments; i ++ ) {
  23738. const u = i / segments;
  23739. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23740. }
  23741. // select an initial normal vector perpendicular to the first tangent vector,
  23742. // and in the direction of the minimum tangent xyz component
  23743. normals[ 0 ] = new Vector3();
  23744. binormals[ 0 ] = new Vector3();
  23745. let min = Number.MAX_VALUE;
  23746. const tx = Math.abs( tangents[ 0 ].x );
  23747. const ty = Math.abs( tangents[ 0 ].y );
  23748. const tz = Math.abs( tangents[ 0 ].z );
  23749. if ( tx <= min ) {
  23750. min = tx;
  23751. normal.set( 1, 0, 0 );
  23752. }
  23753. if ( ty <= min ) {
  23754. min = ty;
  23755. normal.set( 0, 1, 0 );
  23756. }
  23757. if ( tz <= min ) {
  23758. normal.set( 0, 0, 1 );
  23759. }
  23760. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23761. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23762. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23763. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23764. for ( let i = 1; i <= segments; i ++ ) {
  23765. normals[ i ] = normals[ i - 1 ].clone();
  23766. binormals[ i ] = binormals[ i - 1 ].clone();
  23767. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23768. if ( vec.length() > Number.EPSILON ) {
  23769. vec.normalize();
  23770. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23771. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23772. }
  23773. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23774. }
  23775. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23776. if ( closed === true ) {
  23777. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23778. theta /= segments;
  23779. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23780. theta = - theta;
  23781. }
  23782. for ( let i = 1; i <= segments; i ++ ) {
  23783. // twist a little...
  23784. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23785. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23786. }
  23787. }
  23788. return {
  23789. tangents: tangents,
  23790. normals: normals,
  23791. binormals: binormals
  23792. };
  23793. }
  23794. /**
  23795. * Returns a new curve with copied values from this instance.
  23796. *
  23797. * @return {Curve} A clone of this instance.
  23798. */
  23799. clone() {
  23800. return new this.constructor().copy( this );
  23801. }
  23802. /**
  23803. * Copies the values of the given curve to this instance.
  23804. *
  23805. * @param {Curve} source - The curve to copy.
  23806. * @return {Curve} A reference to this curve.
  23807. */
  23808. copy( source ) {
  23809. this.arcLengthDivisions = source.arcLengthDivisions;
  23810. return this;
  23811. }
  23812. /**
  23813. * Serializes the curve into JSON.
  23814. *
  23815. * @return {Object} A JSON object representing the serialized curve.
  23816. * @see {@link ObjectLoader#parse}
  23817. */
  23818. toJSON() {
  23819. const data = {
  23820. metadata: {
  23821. version: 4.7,
  23822. type: 'Curve',
  23823. generator: 'Curve.toJSON'
  23824. }
  23825. };
  23826. data.arcLengthDivisions = this.arcLengthDivisions;
  23827. data.type = this.type;
  23828. return data;
  23829. }
  23830. /**
  23831. * Deserializes the curve from the given JSON.
  23832. *
  23833. * @param {Object} json - The JSON holding the serialized curve.
  23834. * @return {Curve} A reference to this curve.
  23835. */
  23836. fromJSON( json ) {
  23837. this.arcLengthDivisions = json.arcLengthDivisions;
  23838. return this;
  23839. }
  23840. }
  23841. /**
  23842. * A curve representing an ellipse.
  23843. *
  23844. * ```js
  23845. * const curve = new THREE.EllipseCurve(
  23846. * 0, 0,
  23847. * 10, 10,
  23848. * 0, 2 * Math.PI,
  23849. * false,
  23850. * 0
  23851. * );
  23852. *
  23853. * const points = curve.getPoints( 50 );
  23854. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23855. *
  23856. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23857. *
  23858. * // Create the final object to add to the scene
  23859. * const ellipse = new THREE.Line( geometry, material );
  23860. * ```
  23861. *
  23862. * @augments Curve
  23863. */
  23864. class EllipseCurve extends Curve {
  23865. /**
  23866. * Constructs a new ellipse curve.
  23867. *
  23868. * @param {number} [aX=0] - The X center of the ellipse.
  23869. * @param {number} [aY=0] - The Y center of the ellipse.
  23870. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23871. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23872. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23873. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23874. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23875. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23876. */
  23877. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23878. super();
  23879. /**
  23880. * This flag can be used for type testing.
  23881. *
  23882. * @type {boolean}
  23883. * @readonly
  23884. * @default true
  23885. */
  23886. this.isEllipseCurve = true;
  23887. this.type = 'EllipseCurve';
  23888. /**
  23889. * The X center of the ellipse.
  23890. *
  23891. * @type {number}
  23892. * @default 0
  23893. */
  23894. this.aX = aX;
  23895. /**
  23896. * The Y center of the ellipse.
  23897. *
  23898. * @type {number}
  23899. * @default 0
  23900. */
  23901. this.aY = aY;
  23902. /**
  23903. * The radius of the ellipse in the x direction.
  23904. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23905. *
  23906. * @type {number}
  23907. * @default 1
  23908. */
  23909. this.xRadius = xRadius;
  23910. /**
  23911. * The radius of the ellipse in the y direction.
  23912. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23913. *
  23914. * @type {number}
  23915. * @default 1
  23916. */
  23917. this.yRadius = yRadius;
  23918. /**
  23919. * The start angle of the curve in radians starting from the positive X axis.
  23920. *
  23921. * @type {number}
  23922. * @default 0
  23923. */
  23924. this.aStartAngle = aStartAngle;
  23925. /**
  23926. * The end angle of the curve in radians starting from the positive X axis.
  23927. *
  23928. * @type {number}
  23929. * @default Math.PI*2
  23930. */
  23931. this.aEndAngle = aEndAngle;
  23932. /**
  23933. * Whether the ellipse is drawn clockwise or not.
  23934. *
  23935. * @type {boolean}
  23936. * @default false
  23937. */
  23938. this.aClockwise = aClockwise;
  23939. /**
  23940. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23941. *
  23942. * @type {number}
  23943. * @default 0
  23944. */
  23945. this.aRotation = aRotation;
  23946. }
  23947. /**
  23948. * Returns a point on the curve.
  23949. *
  23950. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23951. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23952. * @return {Vector2} The position on the curve.
  23953. */
  23954. getPoint( t, optionalTarget = new Vector2() ) {
  23955. const point = optionalTarget;
  23956. const twoPi = Math.PI * 2;
  23957. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23958. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23959. // ensures that deltaAngle is 0 .. 2 PI
  23960. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23961. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23962. if ( deltaAngle < Number.EPSILON ) {
  23963. if ( samePoints ) {
  23964. deltaAngle = 0;
  23965. } else {
  23966. deltaAngle = twoPi;
  23967. }
  23968. }
  23969. if ( this.aClockwise === true && ! samePoints ) {
  23970. if ( deltaAngle === twoPi ) {
  23971. deltaAngle = - twoPi;
  23972. } else {
  23973. deltaAngle = deltaAngle - twoPi;
  23974. }
  23975. }
  23976. const angle = this.aStartAngle + t * deltaAngle;
  23977. let x = this.aX + this.xRadius * Math.cos( angle );
  23978. let y = this.aY + this.yRadius * Math.sin( angle );
  23979. if ( this.aRotation !== 0 ) {
  23980. const cos = Math.cos( this.aRotation );
  23981. const sin = Math.sin( this.aRotation );
  23982. const tx = x - this.aX;
  23983. const ty = y - this.aY;
  23984. // Rotate the point about the center of the ellipse.
  23985. x = tx * cos - ty * sin + this.aX;
  23986. y = tx * sin + ty * cos + this.aY;
  23987. }
  23988. return point.set( x, y );
  23989. }
  23990. copy( source ) {
  23991. super.copy( source );
  23992. this.aX = source.aX;
  23993. this.aY = source.aY;
  23994. this.xRadius = source.xRadius;
  23995. this.yRadius = source.yRadius;
  23996. this.aStartAngle = source.aStartAngle;
  23997. this.aEndAngle = source.aEndAngle;
  23998. this.aClockwise = source.aClockwise;
  23999. this.aRotation = source.aRotation;
  24000. return this;
  24001. }
  24002. toJSON() {
  24003. const data = super.toJSON();
  24004. data.aX = this.aX;
  24005. data.aY = this.aY;
  24006. data.xRadius = this.xRadius;
  24007. data.yRadius = this.yRadius;
  24008. data.aStartAngle = this.aStartAngle;
  24009. data.aEndAngle = this.aEndAngle;
  24010. data.aClockwise = this.aClockwise;
  24011. data.aRotation = this.aRotation;
  24012. return data;
  24013. }
  24014. fromJSON( json ) {
  24015. super.fromJSON( json );
  24016. this.aX = json.aX;
  24017. this.aY = json.aY;
  24018. this.xRadius = json.xRadius;
  24019. this.yRadius = json.yRadius;
  24020. this.aStartAngle = json.aStartAngle;
  24021. this.aEndAngle = json.aEndAngle;
  24022. this.aClockwise = json.aClockwise;
  24023. this.aRotation = json.aRotation;
  24024. return this;
  24025. }
  24026. }
  24027. /**
  24028. * A curve representing an arc.
  24029. *
  24030. * @augments EllipseCurve
  24031. */
  24032. class ArcCurve extends EllipseCurve {
  24033. /**
  24034. * Constructs a new arc curve.
  24035. *
  24036. * @param {number} [aX=0] - The X center of the ellipse.
  24037. * @param {number} [aY=0] - The Y center of the ellipse.
  24038. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  24039. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  24040. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  24041. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  24042. */
  24043. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24044. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24045. /**
  24046. * This flag can be used for type testing.
  24047. *
  24048. * @type {boolean}
  24049. * @readonly
  24050. * @default true
  24051. */
  24052. this.isArcCurve = true;
  24053. this.type = 'ArcCurve';
  24054. }
  24055. }
  24056. function CubicPoly() {
  24057. /**
  24058. * Centripetal CatmullRom Curve - which is useful for avoiding
  24059. * cusps and self-intersections in non-uniform catmull rom curves.
  24060. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24061. *
  24062. * curve.type accepts centripetal(default), chordal and catmullrom
  24063. * curve.tension is used for catmullrom which defaults to 0.5
  24064. */
  24065. /*
  24066. Based on an optimized c++ solution in
  24067. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24068. - http://ideone.com/NoEbVM
  24069. This CubicPoly class could be used for reusing some variables and calculations,
  24070. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24071. which can be placed in CurveUtils.
  24072. */
  24073. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  24074. /*
  24075. * Compute coefficients for a cubic polynomial
  24076. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24077. * such that
  24078. * p(0) = x0, p(1) = x1
  24079. * and
  24080. * p'(0) = t0, p'(1) = t1.
  24081. */
  24082. function init( x0, x1, t0, t1 ) {
  24083. c0 = x0;
  24084. c1 = t0;
  24085. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  24086. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24087. }
  24088. return {
  24089. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  24090. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24091. },
  24092. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24093. // compute tangents when parameterized in [t1,t2]
  24094. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24095. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24096. // rescale tangents for parametrization in [0,1]
  24097. t1 *= dt1;
  24098. t2 *= dt1;
  24099. init( x1, x2, t1, t2 );
  24100. },
  24101. calc: function ( t ) {
  24102. const t2 = t * t;
  24103. const t3 = t2 * t;
  24104. return c0 + c1 * t + c2 * t2 + c3 * t3;
  24105. }
  24106. };
  24107. }
  24108. //
  24109. const tmp = /*@__PURE__*/ new Vector3();
  24110. const px = /*@__PURE__*/ new CubicPoly();
  24111. const py = /*@__PURE__*/ new CubicPoly();
  24112. const pz = /*@__PURE__*/ new CubicPoly();
  24113. /**
  24114. * A curve representing a Catmull-Rom spline.
  24115. *
  24116. * ```js
  24117. * //Create a closed wavey loop
  24118. * const curve = new THREE.CatmullRomCurve3( [
  24119. * new THREE.Vector3( -10, 0, 10 ),
  24120. * new THREE.Vector3( -5, 5, 5 ),
  24121. * new THREE.Vector3( 0, 0, 0 ),
  24122. * new THREE.Vector3( 5, -5, 5 ),
  24123. * new THREE.Vector3( 10, 0, 10 )
  24124. * ] );
  24125. *
  24126. * const points = curve.getPoints( 50 );
  24127. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24128. *
  24129. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24130. *
  24131. * // Create the final object to add to the scene
  24132. * const curveObject = new THREE.Line( geometry, material );
  24133. * ```
  24134. *
  24135. * @augments Curve
  24136. */
  24137. class CatmullRomCurve3 extends Curve {
  24138. /**
  24139. * Constructs a new Catmull-Rom curve.
  24140. *
  24141. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  24142. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  24143. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  24144. * @param {number} [tension=0.5] - Tension of the curve.
  24145. */
  24146. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  24147. super();
  24148. /**
  24149. * This flag can be used for type testing.
  24150. *
  24151. * @type {boolean}
  24152. * @readonly
  24153. * @default true
  24154. */
  24155. this.isCatmullRomCurve3 = true;
  24156. this.type = 'CatmullRomCurve3';
  24157. /**
  24158. * An array of 3D points defining the curve.
  24159. *
  24160. * @type {Array<Vector3>}
  24161. */
  24162. this.points = points;
  24163. /**
  24164. * Whether the curve is closed or not.
  24165. *
  24166. * @type {boolean}
  24167. * @default false
  24168. */
  24169. this.closed = closed;
  24170. /**
  24171. * The curve type.
  24172. *
  24173. * @type {('centripetal'|'chordal'|'catmullrom')}
  24174. * @default 'centripetal'
  24175. */
  24176. this.curveType = curveType;
  24177. /**
  24178. * Tension of the curve.
  24179. *
  24180. * @type {number}
  24181. * @default 0.5
  24182. */
  24183. this.tension = tension;
  24184. }
  24185. /**
  24186. * Returns a point on the curve.
  24187. *
  24188. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24189. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24190. * @return {Vector3} The position on the curve.
  24191. */
  24192. getPoint( t, optionalTarget = new Vector3() ) {
  24193. const point = optionalTarget;
  24194. const points = this.points;
  24195. const l = points.length;
  24196. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24197. let intPoint = Math.floor( p );
  24198. let weight = p - intPoint;
  24199. if ( this.closed ) {
  24200. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  24201. } else if ( weight === 0 && intPoint === l - 1 ) {
  24202. intPoint = l - 2;
  24203. weight = 1;
  24204. }
  24205. let p0, p3; // 4 points (p1 & p2 defined below)
  24206. if ( this.closed || intPoint > 0 ) {
  24207. p0 = points[ ( intPoint - 1 ) % l ];
  24208. } else {
  24209. // extrapolate first point
  24210. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24211. p0 = tmp;
  24212. }
  24213. const p1 = points[ intPoint % l ];
  24214. const p2 = points[ ( intPoint + 1 ) % l ];
  24215. if ( this.closed || intPoint + 2 < l ) {
  24216. p3 = points[ ( intPoint + 2 ) % l ];
  24217. } else {
  24218. // extrapolate last point
  24219. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24220. p3 = tmp;
  24221. }
  24222. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  24223. // init Centripetal / Chordal Catmull-Rom
  24224. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  24225. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24226. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24227. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24228. // safety check for repeated points
  24229. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24230. if ( dt0 < 1e-4 ) dt0 = dt1;
  24231. if ( dt2 < 1e-4 ) dt2 = dt1;
  24232. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24233. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24234. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24235. } else if ( this.curveType === 'catmullrom' ) {
  24236. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  24237. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  24238. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  24239. }
  24240. point.set(
  24241. px.calc( weight ),
  24242. py.calc( weight ),
  24243. pz.calc( weight )
  24244. );
  24245. return point;
  24246. }
  24247. copy( source ) {
  24248. super.copy( source );
  24249. this.points = [];
  24250. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24251. const point = source.points[ i ];
  24252. this.points.push( point.clone() );
  24253. }
  24254. this.closed = source.closed;
  24255. this.curveType = source.curveType;
  24256. this.tension = source.tension;
  24257. return this;
  24258. }
  24259. toJSON() {
  24260. const data = super.toJSON();
  24261. data.points = [];
  24262. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24263. const point = this.points[ i ];
  24264. data.points.push( point.toArray() );
  24265. }
  24266. data.closed = this.closed;
  24267. data.curveType = this.curveType;
  24268. data.tension = this.tension;
  24269. return data;
  24270. }
  24271. fromJSON( json ) {
  24272. super.fromJSON( json );
  24273. this.points = [];
  24274. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24275. const point = json.points[ i ];
  24276. this.points.push( new Vector3().fromArray( point ) );
  24277. }
  24278. this.closed = json.closed;
  24279. this.curveType = json.curveType;
  24280. this.tension = json.tension;
  24281. return this;
  24282. }
  24283. }
  24284. /**
  24285. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  24286. *
  24287. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  24288. *
  24289. * @module Interpolations
  24290. */
  24291. /**
  24292. * Computes a point on a Catmull-Rom spline.
  24293. *
  24294. * @param {number} t - The interpolation factor.
  24295. * @param {number} p0 - The first control point.
  24296. * @param {number} p1 - The second control point.
  24297. * @param {number} p2 - The third control point.
  24298. * @param {number} p3 - The fourth control point.
  24299. * @return {number} The calculated point on a Catmull-Rom spline.
  24300. */
  24301. function CatmullRom( t, p0, p1, p2, p3 ) {
  24302. const v0 = ( p2 - p0 ) * 0.5;
  24303. const v1 = ( p3 - p1 ) * 0.5;
  24304. const t2 = t * t;
  24305. const t3 = t * t2;
  24306. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  24307. }
  24308. //
  24309. function QuadraticBezierP0( t, p ) {
  24310. const k = 1 - t;
  24311. return k * k * p;
  24312. }
  24313. function QuadraticBezierP1( t, p ) {
  24314. return 2 * ( 1 - t ) * t * p;
  24315. }
  24316. function QuadraticBezierP2( t, p ) {
  24317. return t * t * p;
  24318. }
  24319. /**
  24320. * Computes a point on a Quadratic Bezier curve.
  24321. *
  24322. * @param {number} t - The interpolation factor.
  24323. * @param {number} p0 - The first control point.
  24324. * @param {number} p1 - The second control point.
  24325. * @param {number} p2 - The third control point.
  24326. * @return {number} The calculated point on a Quadratic Bezier curve.
  24327. */
  24328. function QuadraticBezier( t, p0, p1, p2 ) {
  24329. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  24330. QuadraticBezierP2( t, p2 );
  24331. }
  24332. //
  24333. function CubicBezierP0( t, p ) {
  24334. const k = 1 - t;
  24335. return k * k * k * p;
  24336. }
  24337. function CubicBezierP1( t, p ) {
  24338. const k = 1 - t;
  24339. return 3 * k * k * t * p;
  24340. }
  24341. function CubicBezierP2( t, p ) {
  24342. return 3 * ( 1 - t ) * t * t * p;
  24343. }
  24344. function CubicBezierP3( t, p ) {
  24345. return t * t * t * p;
  24346. }
  24347. /**
  24348. * Computes a point on a Cubic Bezier curve.
  24349. *
  24350. * @param {number} t - The interpolation factor.
  24351. * @param {number} p0 - The first control point.
  24352. * @param {number} p1 - The second control point.
  24353. * @param {number} p2 - The third control point.
  24354. * @param {number} p3 - The fourth control point.
  24355. * @return {number} The calculated point on a Cubic Bezier curve.
  24356. */
  24357. function CubicBezier( t, p0, p1, p2, p3 ) {
  24358. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  24359. CubicBezierP3( t, p3 );
  24360. }
  24361. /**
  24362. * A curve representing a 2D Cubic Bezier curve.
  24363. *
  24364. * ```js
  24365. * const curve = new THREE.CubicBezierCurve(
  24366. * new THREE.Vector2( - 0, 0 ),
  24367. * new THREE.Vector2( - 5, 15 ),
  24368. * new THREE.Vector2( 20, 15 ),
  24369. * new THREE.Vector2( 10, 0 )
  24370. * );
  24371. *
  24372. * const points = curve.getPoints( 50 );
  24373. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24374. *
  24375. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24376. *
  24377. * // Create the final object to add to the scene
  24378. * const curveObject = new THREE.Line( geometry, material );
  24379. * ```
  24380. *
  24381. * @augments Curve
  24382. */
  24383. class CubicBezierCurve extends Curve {
  24384. /**
  24385. * Constructs a new Cubic Bezier curve.
  24386. *
  24387. * @param {Vector2} [v0] - The start point.
  24388. * @param {Vector2} [v1] - The first control point.
  24389. * @param {Vector2} [v2] - The second control point.
  24390. * @param {Vector2} [v3] - The end point.
  24391. */
  24392. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  24393. super();
  24394. /**
  24395. * This flag can be used for type testing.
  24396. *
  24397. * @type {boolean}
  24398. * @readonly
  24399. * @default true
  24400. */
  24401. this.isCubicBezierCurve = true;
  24402. this.type = 'CubicBezierCurve';
  24403. /**
  24404. * The start point.
  24405. *
  24406. * @type {Vector2}
  24407. */
  24408. this.v0 = v0;
  24409. /**
  24410. * The first control point.
  24411. *
  24412. * @type {Vector2}
  24413. */
  24414. this.v1 = v1;
  24415. /**
  24416. * The second control point.
  24417. *
  24418. * @type {Vector2}
  24419. */
  24420. this.v2 = v2;
  24421. /**
  24422. * The end point.
  24423. *
  24424. * @type {Vector2}
  24425. */
  24426. this.v3 = v3;
  24427. }
  24428. /**
  24429. * Returns a point on the curve.
  24430. *
  24431. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24432. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24433. * @return {Vector2} The position on the curve.
  24434. */
  24435. getPoint( t, optionalTarget = new Vector2() ) {
  24436. const point = optionalTarget;
  24437. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24438. point.set(
  24439. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24440. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24441. );
  24442. return point;
  24443. }
  24444. copy( source ) {
  24445. super.copy( source );
  24446. this.v0.copy( source.v0 );
  24447. this.v1.copy( source.v1 );
  24448. this.v2.copy( source.v2 );
  24449. this.v3.copy( source.v3 );
  24450. return this;
  24451. }
  24452. toJSON() {
  24453. const data = super.toJSON();
  24454. data.v0 = this.v0.toArray();
  24455. data.v1 = this.v1.toArray();
  24456. data.v2 = this.v2.toArray();
  24457. data.v3 = this.v3.toArray();
  24458. return data;
  24459. }
  24460. fromJSON( json ) {
  24461. super.fromJSON( json );
  24462. this.v0.fromArray( json.v0 );
  24463. this.v1.fromArray( json.v1 );
  24464. this.v2.fromArray( json.v2 );
  24465. this.v3.fromArray( json.v3 );
  24466. return this;
  24467. }
  24468. }
  24469. /**
  24470. * A curve representing a 3D Cubic Bezier curve.
  24471. *
  24472. * @augments Curve
  24473. */
  24474. class CubicBezierCurve3 extends Curve {
  24475. /**
  24476. * Constructs a new Cubic Bezier curve.
  24477. *
  24478. * @param {Vector3} [v0] - The start point.
  24479. * @param {Vector3} [v1] - The first control point.
  24480. * @param {Vector3} [v2] - The second control point.
  24481. * @param {Vector3} [v3] - The end point.
  24482. */
  24483. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24484. super();
  24485. /**
  24486. * This flag can be used for type testing.
  24487. *
  24488. * @type {boolean}
  24489. * @readonly
  24490. * @default true
  24491. */
  24492. this.isCubicBezierCurve3 = true;
  24493. this.type = 'CubicBezierCurve3';
  24494. /**
  24495. * The start point.
  24496. *
  24497. * @type {Vector3}
  24498. */
  24499. this.v0 = v0;
  24500. /**
  24501. * The first control point.
  24502. *
  24503. * @type {Vector3}
  24504. */
  24505. this.v1 = v1;
  24506. /**
  24507. * The second control point.
  24508. *
  24509. * @type {Vector3}
  24510. */
  24511. this.v2 = v2;
  24512. /**
  24513. * The end point.
  24514. *
  24515. * @type {Vector3}
  24516. */
  24517. this.v3 = v3;
  24518. }
  24519. /**
  24520. * Returns a point on the curve.
  24521. *
  24522. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24523. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24524. * @return {Vector3} The position on the curve.
  24525. */
  24526. getPoint( t, optionalTarget = new Vector3() ) {
  24527. const point = optionalTarget;
  24528. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24529. point.set(
  24530. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24531. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24532. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24533. );
  24534. return point;
  24535. }
  24536. copy( source ) {
  24537. super.copy( source );
  24538. this.v0.copy( source.v0 );
  24539. this.v1.copy( source.v1 );
  24540. this.v2.copy( source.v2 );
  24541. this.v3.copy( source.v3 );
  24542. return this;
  24543. }
  24544. toJSON() {
  24545. const data = super.toJSON();
  24546. data.v0 = this.v0.toArray();
  24547. data.v1 = this.v1.toArray();
  24548. data.v2 = this.v2.toArray();
  24549. data.v3 = this.v3.toArray();
  24550. return data;
  24551. }
  24552. fromJSON( json ) {
  24553. super.fromJSON( json );
  24554. this.v0.fromArray( json.v0 );
  24555. this.v1.fromArray( json.v1 );
  24556. this.v2.fromArray( json.v2 );
  24557. this.v3.fromArray( json.v3 );
  24558. return this;
  24559. }
  24560. }
  24561. /**
  24562. * A curve representing a 2D line segment.
  24563. *
  24564. * @augments Curve
  24565. */
  24566. class LineCurve extends Curve {
  24567. /**
  24568. * Constructs a new line curve.
  24569. *
  24570. * @param {Vector2} [v1] - The start point.
  24571. * @param {Vector2} [v2] - The end point.
  24572. */
  24573. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24574. super();
  24575. /**
  24576. * This flag can be used for type testing.
  24577. *
  24578. * @type {boolean}
  24579. * @readonly
  24580. * @default true
  24581. */
  24582. this.isLineCurve = true;
  24583. this.type = 'LineCurve';
  24584. /**
  24585. * The start point.
  24586. *
  24587. * @type {Vector2}
  24588. */
  24589. this.v1 = v1;
  24590. /**
  24591. * The end point.
  24592. *
  24593. * @type {Vector2}
  24594. */
  24595. this.v2 = v2;
  24596. }
  24597. /**
  24598. * Returns a point on the line.
  24599. *
  24600. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24601. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24602. * @return {Vector2} The position on the line.
  24603. */
  24604. getPoint( t, optionalTarget = new Vector2() ) {
  24605. const point = optionalTarget;
  24606. if ( t === 1 ) {
  24607. point.copy( this.v2 );
  24608. } else {
  24609. point.copy( this.v2 ).sub( this.v1 );
  24610. point.multiplyScalar( t ).add( this.v1 );
  24611. }
  24612. return point;
  24613. }
  24614. // Line curve is linear, so we can overwrite default getPointAt
  24615. getPointAt( u, optionalTarget ) {
  24616. return this.getPoint( u, optionalTarget );
  24617. }
  24618. getTangent( t, optionalTarget = new Vector2() ) {
  24619. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24620. }
  24621. getTangentAt( u, optionalTarget ) {
  24622. return this.getTangent( u, optionalTarget );
  24623. }
  24624. copy( source ) {
  24625. super.copy( source );
  24626. this.v1.copy( source.v1 );
  24627. this.v2.copy( source.v2 );
  24628. return this;
  24629. }
  24630. toJSON() {
  24631. const data = super.toJSON();
  24632. data.v1 = this.v1.toArray();
  24633. data.v2 = this.v2.toArray();
  24634. return data;
  24635. }
  24636. fromJSON( json ) {
  24637. super.fromJSON( json );
  24638. this.v1.fromArray( json.v1 );
  24639. this.v2.fromArray( json.v2 );
  24640. return this;
  24641. }
  24642. }
  24643. /**
  24644. * A curve representing a 3D line segment.
  24645. *
  24646. * @augments Curve
  24647. */
  24648. class LineCurve3 extends Curve {
  24649. /**
  24650. * Constructs a new line curve.
  24651. *
  24652. * @param {Vector3} [v1] - The start point.
  24653. * @param {Vector3} [v2] - The end point.
  24654. */
  24655. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24656. super();
  24657. /**
  24658. * This flag can be used for type testing.
  24659. *
  24660. * @type {boolean}
  24661. * @readonly
  24662. * @default true
  24663. */
  24664. this.isLineCurve3 = true;
  24665. this.type = 'LineCurve3';
  24666. /**
  24667. * The start point.
  24668. *
  24669. * @type {Vector3}
  24670. */
  24671. this.v1 = v1;
  24672. /**
  24673. * The end point.
  24674. *
  24675. * @type {Vector2}
  24676. */
  24677. this.v2 = v2;
  24678. }
  24679. /**
  24680. * Returns a point on the line.
  24681. *
  24682. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24683. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24684. * @return {Vector3} The position on the line.
  24685. */
  24686. getPoint( t, optionalTarget = new Vector3() ) {
  24687. const point = optionalTarget;
  24688. if ( t === 1 ) {
  24689. point.copy( this.v2 );
  24690. } else {
  24691. point.copy( this.v2 ).sub( this.v1 );
  24692. point.multiplyScalar( t ).add( this.v1 );
  24693. }
  24694. return point;
  24695. }
  24696. // Line curve is linear, so we can overwrite default getPointAt
  24697. getPointAt( u, optionalTarget ) {
  24698. return this.getPoint( u, optionalTarget );
  24699. }
  24700. getTangent( t, optionalTarget = new Vector3() ) {
  24701. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24702. }
  24703. getTangentAt( u, optionalTarget ) {
  24704. return this.getTangent( u, optionalTarget );
  24705. }
  24706. copy( source ) {
  24707. super.copy( source );
  24708. this.v1.copy( source.v1 );
  24709. this.v2.copy( source.v2 );
  24710. return this;
  24711. }
  24712. toJSON() {
  24713. const data = super.toJSON();
  24714. data.v1 = this.v1.toArray();
  24715. data.v2 = this.v2.toArray();
  24716. return data;
  24717. }
  24718. fromJSON( json ) {
  24719. super.fromJSON( json );
  24720. this.v1.fromArray( json.v1 );
  24721. this.v2.fromArray( json.v2 );
  24722. return this;
  24723. }
  24724. }
  24725. /**
  24726. * A curve representing a 2D Quadratic Bezier curve.
  24727. *
  24728. * ```js
  24729. * const curve = new THREE.QuadraticBezierCurve(
  24730. * new THREE.Vector2( - 10, 0 ),
  24731. * new THREE.Vector2( 20, 15 ),
  24732. * new THREE.Vector2( 10, 0 )
  24733. * )
  24734. *
  24735. * const points = curve.getPoints( 50 );
  24736. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24737. *
  24738. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24739. *
  24740. * // Create the final object to add to the scene
  24741. * const curveObject = new THREE.Line( geometry, material );
  24742. * ```
  24743. *
  24744. * @augments Curve
  24745. */
  24746. class QuadraticBezierCurve extends Curve {
  24747. /**
  24748. * Constructs a new Quadratic Bezier curve.
  24749. *
  24750. * @param {Vector2} [v0] - The start point.
  24751. * @param {Vector2} [v1] - The control point.
  24752. * @param {Vector2} [v2] - The end point.
  24753. */
  24754. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24755. super();
  24756. /**
  24757. * This flag can be used for type testing.
  24758. *
  24759. * @type {boolean}
  24760. * @readonly
  24761. * @default true
  24762. */
  24763. this.isQuadraticBezierCurve = true;
  24764. this.type = 'QuadraticBezierCurve';
  24765. /**
  24766. * The start point.
  24767. *
  24768. * @type {Vector2}
  24769. */
  24770. this.v0 = v0;
  24771. /**
  24772. * The control point.
  24773. *
  24774. * @type {Vector2}
  24775. */
  24776. this.v1 = v1;
  24777. /**
  24778. * The end point.
  24779. *
  24780. * @type {Vector2}
  24781. */
  24782. this.v2 = v2;
  24783. }
  24784. /**
  24785. * Returns a point on the curve.
  24786. *
  24787. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24788. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24789. * @return {Vector2} The position on the curve.
  24790. */
  24791. getPoint( t, optionalTarget = new Vector2() ) {
  24792. const point = optionalTarget;
  24793. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24794. point.set(
  24795. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24796. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24797. );
  24798. return point;
  24799. }
  24800. copy( source ) {
  24801. super.copy( source );
  24802. this.v0.copy( source.v0 );
  24803. this.v1.copy( source.v1 );
  24804. this.v2.copy( source.v2 );
  24805. return this;
  24806. }
  24807. toJSON() {
  24808. const data = super.toJSON();
  24809. data.v0 = this.v0.toArray();
  24810. data.v1 = this.v1.toArray();
  24811. data.v2 = this.v2.toArray();
  24812. return data;
  24813. }
  24814. fromJSON( json ) {
  24815. super.fromJSON( json );
  24816. this.v0.fromArray( json.v0 );
  24817. this.v1.fromArray( json.v1 );
  24818. this.v2.fromArray( json.v2 );
  24819. return this;
  24820. }
  24821. }
  24822. /**
  24823. * A curve representing a 3D Quadratic Bezier curve.
  24824. *
  24825. * @augments Curve
  24826. */
  24827. class QuadraticBezierCurve3 extends Curve {
  24828. /**
  24829. * Constructs a new Quadratic Bezier curve.
  24830. *
  24831. * @param {Vector3} [v0] - The start point.
  24832. * @param {Vector3} [v1] - The control point.
  24833. * @param {Vector3} [v2] - The end point.
  24834. */
  24835. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24836. super();
  24837. /**
  24838. * This flag can be used for type testing.
  24839. *
  24840. * @type {boolean}
  24841. * @readonly
  24842. * @default true
  24843. */
  24844. this.isQuadraticBezierCurve3 = true;
  24845. this.type = 'QuadraticBezierCurve3';
  24846. /**
  24847. * The start point.
  24848. *
  24849. * @type {Vector3}
  24850. */
  24851. this.v0 = v0;
  24852. /**
  24853. * The control point.
  24854. *
  24855. * @type {Vector3}
  24856. */
  24857. this.v1 = v1;
  24858. /**
  24859. * The end point.
  24860. *
  24861. * @type {Vector3}
  24862. */
  24863. this.v2 = v2;
  24864. }
  24865. /**
  24866. * Returns a point on the curve.
  24867. *
  24868. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24869. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24870. * @return {Vector3} The position on the curve.
  24871. */
  24872. getPoint( t, optionalTarget = new Vector3() ) {
  24873. const point = optionalTarget;
  24874. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24875. point.set(
  24876. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24877. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24878. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24879. );
  24880. return point;
  24881. }
  24882. copy( source ) {
  24883. super.copy( source );
  24884. this.v0.copy( source.v0 );
  24885. this.v1.copy( source.v1 );
  24886. this.v2.copy( source.v2 );
  24887. return this;
  24888. }
  24889. toJSON() {
  24890. const data = super.toJSON();
  24891. data.v0 = this.v0.toArray();
  24892. data.v1 = this.v1.toArray();
  24893. data.v2 = this.v2.toArray();
  24894. return data;
  24895. }
  24896. fromJSON( json ) {
  24897. super.fromJSON( json );
  24898. this.v0.fromArray( json.v0 );
  24899. this.v1.fromArray( json.v1 );
  24900. this.v2.fromArray( json.v2 );
  24901. return this;
  24902. }
  24903. }
  24904. /**
  24905. * A curve representing a 2D spline curve.
  24906. *
  24907. * ```js
  24908. * // Create a sine-like wave
  24909. * const curve = new THREE.SplineCurve( [
  24910. * new THREE.Vector2( -10, 0 ),
  24911. * new THREE.Vector2( -5, 5 ),
  24912. * new THREE.Vector2( 0, 0 ),
  24913. * new THREE.Vector2( 5, -5 ),
  24914. * new THREE.Vector2( 10, 0 )
  24915. * ] );
  24916. *
  24917. * const points = curve.getPoints( 50 );
  24918. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24919. *
  24920. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24921. *
  24922. * // Create the final object to add to the scene
  24923. * const splineObject = new THREE.Line( geometry, material );
  24924. * ```
  24925. *
  24926. * @augments Curve
  24927. */
  24928. class SplineCurve extends Curve {
  24929. /**
  24930. * Constructs a new 2D spline curve.
  24931. *
  24932. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24933. */
  24934. constructor( points = [] ) {
  24935. super();
  24936. /**
  24937. * This flag can be used for type testing.
  24938. *
  24939. * @type {boolean}
  24940. * @readonly
  24941. * @default true
  24942. */
  24943. this.isSplineCurve = true;
  24944. this.type = 'SplineCurve';
  24945. /**
  24946. * An array of 2D points defining the curve.
  24947. *
  24948. * @type {Array<Vector2>}
  24949. */
  24950. this.points = points;
  24951. }
  24952. /**
  24953. * Returns a point on the curve.
  24954. *
  24955. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24956. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24957. * @return {Vector2} The position on the curve.
  24958. */
  24959. getPoint( t, optionalTarget = new Vector2() ) {
  24960. const point = optionalTarget;
  24961. const points = this.points;
  24962. const p = ( points.length - 1 ) * t;
  24963. const intPoint = Math.floor( p );
  24964. const weight = p - intPoint;
  24965. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24966. const p1 = points[ intPoint ];
  24967. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24968. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24969. point.set(
  24970. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24971. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24972. );
  24973. return point;
  24974. }
  24975. copy( source ) {
  24976. super.copy( source );
  24977. this.points = [];
  24978. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24979. const point = source.points[ i ];
  24980. this.points.push( point.clone() );
  24981. }
  24982. return this;
  24983. }
  24984. toJSON() {
  24985. const data = super.toJSON();
  24986. data.points = [];
  24987. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24988. const point = this.points[ i ];
  24989. data.points.push( point.toArray() );
  24990. }
  24991. return data;
  24992. }
  24993. fromJSON( json ) {
  24994. super.fromJSON( json );
  24995. this.points = [];
  24996. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24997. const point = json.points[ i ];
  24998. this.points.push( new Vector2().fromArray( point ) );
  24999. }
  25000. return this;
  25001. }
  25002. }
  25003. var Curves = /*#__PURE__*/Object.freeze({
  25004. __proto__: null,
  25005. ArcCurve: ArcCurve,
  25006. CatmullRomCurve3: CatmullRomCurve3,
  25007. CubicBezierCurve: CubicBezierCurve,
  25008. CubicBezierCurve3: CubicBezierCurve3,
  25009. EllipseCurve: EllipseCurve,
  25010. LineCurve: LineCurve,
  25011. LineCurve3: LineCurve3,
  25012. QuadraticBezierCurve: QuadraticBezierCurve,
  25013. QuadraticBezierCurve3: QuadraticBezierCurve3,
  25014. SplineCurve: SplineCurve
  25015. });
  25016. /**
  25017. * A base class extending {@link Curve}. `CurvePath` is simply an
  25018. * array of connected curves, but retains the API of a curve.
  25019. *
  25020. * @augments Curve
  25021. */
  25022. class CurvePath extends Curve {
  25023. /**
  25024. * Constructs a new curve path.
  25025. */
  25026. constructor() {
  25027. super();
  25028. this.type = 'CurvePath';
  25029. /**
  25030. * An array of curves defining the
  25031. * path.
  25032. *
  25033. * @type {Array<Curve>}
  25034. */
  25035. this.curves = [];
  25036. /**
  25037. * Whether the path should automatically be closed
  25038. * by a line curve.
  25039. *
  25040. * @type {boolean}
  25041. * @default false
  25042. */
  25043. this.autoClose = false;
  25044. }
  25045. /**
  25046. * Adds a curve to this curve path.
  25047. *
  25048. * @param {Curve} curve - The curve to add.
  25049. */
  25050. add( curve ) {
  25051. this.curves.push( curve );
  25052. }
  25053. /**
  25054. * Adds a line curve to close the path.
  25055. *
  25056. * @return {CurvePath} A reference to this curve path.
  25057. */
  25058. closePath() {
  25059. // Add a line curve if start and end of lines are not connected
  25060. const startPoint = this.curves[ 0 ].getPoint( 0 );
  25061. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  25062. if ( ! startPoint.equals( endPoint ) ) {
  25063. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  25064. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  25065. }
  25066. return this;
  25067. }
  25068. /**
  25069. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  25070. * for the given interpolation factor.
  25071. *
  25072. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  25073. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  25074. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  25075. */
  25076. getPoint( t, optionalTarget ) {
  25077. // To get accurate point with reference to
  25078. // entire path distance at time t,
  25079. // following has to be done:
  25080. // 1. Length of each sub path have to be known
  25081. // 2. Locate and identify type of curve
  25082. // 3. Get t for the curve
  25083. // 4. Return curve.getPointAt(t')
  25084. const d = t * this.getLength();
  25085. const curveLengths = this.getCurveLengths();
  25086. let i = 0;
  25087. // To think about boundaries points.
  25088. while ( i < curveLengths.length ) {
  25089. if ( curveLengths[ i ] >= d ) {
  25090. const diff = curveLengths[ i ] - d;
  25091. const curve = this.curves[ i ];
  25092. const segmentLength = curve.getLength();
  25093. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  25094. return curve.getPointAt( u, optionalTarget );
  25095. }
  25096. i ++;
  25097. }
  25098. return null;
  25099. // loop where sum != 0, sum > d , sum+1 <d
  25100. }
  25101. getLength() {
  25102. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  25103. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  25104. // getPoint() depends on getLength
  25105. const lens = this.getCurveLengths();
  25106. return lens[ lens.length - 1 ];
  25107. }
  25108. updateArcLengths() {
  25109. // cacheLengths must be recalculated.
  25110. this.needsUpdate = true;
  25111. this.cacheLengths = null;
  25112. this.getCurveLengths();
  25113. }
  25114. /**
  25115. * Returns list of cumulative curve lengths of the defined curves.
  25116. *
  25117. * @return {Array<number>} The curve lengths.
  25118. */
  25119. getCurveLengths() {
  25120. // Compute lengths and cache them
  25121. // We cannot overwrite getLengths() because UtoT mapping uses it.
  25122. // We use cache values if curves and cache array are same length
  25123. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  25124. return this.cacheLengths;
  25125. }
  25126. // Get length of sub-curve
  25127. // Push sums into cached array
  25128. const lengths = [];
  25129. let sums = 0;
  25130. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  25131. sums += this.curves[ i ].getLength();
  25132. lengths.push( sums );
  25133. }
  25134. this.cacheLengths = lengths;
  25135. return lengths;
  25136. }
  25137. getSpacedPoints( divisions = 40 ) {
  25138. const points = [];
  25139. for ( let i = 0; i <= divisions; i ++ ) {
  25140. points.push( this.getPoint( i / divisions ) );
  25141. }
  25142. if ( this.autoClose ) {
  25143. points.push( points[ 0 ] );
  25144. }
  25145. return points;
  25146. }
  25147. getPoints( divisions = 12 ) {
  25148. const points = [];
  25149. let last;
  25150. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  25151. const curve = curves[ i ];
  25152. const resolution = curve.isEllipseCurve ? divisions * 2
  25153. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  25154. : curve.isSplineCurve ? divisions * curve.points.length
  25155. : divisions;
  25156. const pts = curve.getPoints( resolution );
  25157. for ( let j = 0; j < pts.length; j ++ ) {
  25158. const point = pts[ j ];
  25159. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  25160. points.push( point );
  25161. last = point;
  25162. }
  25163. }
  25164. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  25165. points.push( points[ 0 ] );
  25166. }
  25167. return points;
  25168. }
  25169. copy( source ) {
  25170. super.copy( source );
  25171. this.curves = [];
  25172. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  25173. const curve = source.curves[ i ];
  25174. this.curves.push( curve.clone() );
  25175. }
  25176. this.autoClose = source.autoClose;
  25177. return this;
  25178. }
  25179. toJSON() {
  25180. const data = super.toJSON();
  25181. data.autoClose = this.autoClose;
  25182. data.curves = [];
  25183. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  25184. const curve = this.curves[ i ];
  25185. data.curves.push( curve.toJSON() );
  25186. }
  25187. return data;
  25188. }
  25189. fromJSON( json ) {
  25190. super.fromJSON( json );
  25191. this.autoClose = json.autoClose;
  25192. this.curves = [];
  25193. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  25194. const curve = json.curves[ i ];
  25195. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  25196. }
  25197. return this;
  25198. }
  25199. }
  25200. /**
  25201. * A 2D path representation. The class provides methods for creating paths
  25202. * and contours of 2D shapes similar to the 2D Canvas API.
  25203. *
  25204. * ```js
  25205. * const path = new THREE.Path();
  25206. *
  25207. * path.lineTo( 0, 0.8 );
  25208. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  25209. * path.lineTo( 1, 1 );
  25210. *
  25211. * const points = path.getPoints();
  25212. *
  25213. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  25214. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  25215. *
  25216. * const line = new THREE.Line( geometry, material );
  25217. * scene.add( line );
  25218. * ```
  25219. *
  25220. * @augments CurvePath
  25221. */
  25222. class Path extends CurvePath {
  25223. /**
  25224. * Constructs a new path.
  25225. *
  25226. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  25227. */
  25228. constructor( points ) {
  25229. super();
  25230. this.type = 'Path';
  25231. /**
  25232. * The current offset of the path. Any new curve added will start here.
  25233. *
  25234. * @type {Vector2}
  25235. */
  25236. this.currentPoint = new Vector2();
  25237. if ( points ) {
  25238. this.setFromPoints( points );
  25239. }
  25240. }
  25241. /**
  25242. * Creates a path from the given list of points. The points are added
  25243. * to the path as instances of {@link LineCurve}.
  25244. *
  25245. * @param {Array<Vector2>} points - An array of 2D points.
  25246. * @return {Path} A reference to this path.
  25247. */
  25248. setFromPoints( points ) {
  25249. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  25250. for ( let i = 1, l = points.length; i < l; i ++ ) {
  25251. this.lineTo( points[ i ].x, points[ i ].y );
  25252. }
  25253. return this;
  25254. }
  25255. /**
  25256. * Moves {@link Path#currentPoint} to the given point.
  25257. *
  25258. * @param {number} x - The x coordinate.
  25259. * @param {number} y - The y coordinate.
  25260. * @return {Path} A reference to this path.
  25261. */
  25262. moveTo( x, y ) {
  25263. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25264. return this;
  25265. }
  25266. /**
  25267. * Adds an instance of {@link LineCurve} to the path by connecting
  25268. * the current point with the given one.
  25269. *
  25270. * @param {number} x - The x coordinate of the end point.
  25271. * @param {number} y - The y coordinate of the end point.
  25272. * @return {Path} A reference to this path.
  25273. */
  25274. lineTo( x, y ) {
  25275. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25276. this.curves.push( curve );
  25277. this.currentPoint.set( x, y );
  25278. return this;
  25279. }
  25280. /**
  25281. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  25282. * the current point with the given one.
  25283. *
  25284. * @param {number} aCPx - The x coordinate of the control point.
  25285. * @param {number} aCPy - The y coordinate of the control point.
  25286. * @param {number} aX - The x coordinate of the end point.
  25287. * @param {number} aY - The y coordinate of the end point.
  25288. * @return {Path} A reference to this path.
  25289. */
  25290. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  25291. const curve = new QuadraticBezierCurve(
  25292. this.currentPoint.clone(),
  25293. new Vector2( aCPx, aCPy ),
  25294. new Vector2( aX, aY )
  25295. );
  25296. this.curves.push( curve );
  25297. this.currentPoint.set( aX, aY );
  25298. return this;
  25299. }
  25300. /**
  25301. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  25302. * the current point with the given one.
  25303. *
  25304. * @param {number} aCP1x - The x coordinate of the first control point.
  25305. * @param {number} aCP1y - The y coordinate of the first control point.
  25306. * @param {number} aCP2x - The x coordinate of the second control point.
  25307. * @param {number} aCP2y - The y coordinate of the second control point.
  25308. * @param {number} aX - The x coordinate of the end point.
  25309. * @param {number} aY - The y coordinate of the end point.
  25310. * @return {Path} A reference to this path.
  25311. */
  25312. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25313. const curve = new CubicBezierCurve(
  25314. this.currentPoint.clone(),
  25315. new Vector2( aCP1x, aCP1y ),
  25316. new Vector2( aCP2x, aCP2y ),
  25317. new Vector2( aX, aY )
  25318. );
  25319. this.curves.push( curve );
  25320. this.currentPoint.set( aX, aY );
  25321. return this;
  25322. }
  25323. /**
  25324. * Adds an instance of {@link SplineCurve} to the path by connecting
  25325. * the current point with the given list of points.
  25326. *
  25327. * @param {Array<Vector2>} pts - An array of points in 2D space.
  25328. * @return {Path} A reference to this path.
  25329. */
  25330. splineThru( pts ) {
  25331. const npts = [ this.currentPoint.clone() ].concat( pts );
  25332. const curve = new SplineCurve( npts );
  25333. this.curves.push( curve );
  25334. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25335. return this;
  25336. }
  25337. /**
  25338. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  25339. * to the current point.
  25340. *
  25341. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  25342. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  25343. * @param {number} [aRadius=1] - The radius of the arc.
  25344. * @param {number} [aStartAngle=0] - The start angle in radians.
  25345. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25346. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25347. * @return {Path} A reference to this path.
  25348. */
  25349. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25350. const x0 = this.currentPoint.x;
  25351. const y0 = this.currentPoint.y;
  25352. this.absarc( aX + x0, aY + y0, aRadius,
  25353. aStartAngle, aEndAngle, aClockwise );
  25354. return this;
  25355. }
  25356. /**
  25357. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  25358. *
  25359. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  25360. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  25361. * @param {number} [aRadius=1] - The radius of the arc.
  25362. * @param {number} [aStartAngle=0] - The start angle in radians.
  25363. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25364. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25365. * @return {Path} A reference to this path.
  25366. */
  25367. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25368. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25369. return this;
  25370. }
  25371. /**
  25372. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  25373. * to the current point
  25374. *
  25375. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  25376. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  25377. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25378. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25379. * @param {number} [aStartAngle=0] - The start angle in radians.
  25380. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25381. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25382. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25383. * @return {Path} A reference to this path.
  25384. */
  25385. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25386. const x0 = this.currentPoint.x;
  25387. const y0 = this.currentPoint.y;
  25388. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25389. return this;
  25390. }
  25391. /**
  25392. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  25393. *
  25394. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  25395. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  25396. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25397. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25398. * @param {number} [aStartAngle=0] - The start angle in radians.
  25399. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25400. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25401. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25402. * @return {Path} A reference to this path.
  25403. */
  25404. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25405. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25406. if ( this.curves.length > 0 ) {
  25407. // if a previous curve is present, attempt to join
  25408. const firstPoint = curve.getPoint( 0 );
  25409. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25410. this.lineTo( firstPoint.x, firstPoint.y );
  25411. }
  25412. }
  25413. this.curves.push( curve );
  25414. const lastPoint = curve.getPoint( 1 );
  25415. this.currentPoint.copy( lastPoint );
  25416. return this;
  25417. }
  25418. copy( source ) {
  25419. super.copy( source );
  25420. this.currentPoint.copy( source.currentPoint );
  25421. return this;
  25422. }
  25423. toJSON() {
  25424. const data = super.toJSON();
  25425. data.currentPoint = this.currentPoint.toArray();
  25426. return data;
  25427. }
  25428. fromJSON( json ) {
  25429. super.fromJSON( json );
  25430. this.currentPoint.fromArray( json.currentPoint );
  25431. return this;
  25432. }
  25433. }
  25434. /**
  25435. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  25436. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  25437. * points, or to get triangulated faces.
  25438. *
  25439. * ```js
  25440. * const heartShape = new THREE.Shape();
  25441. *
  25442. * heartShape.moveTo( 25, 25 );
  25443. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  25444. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  25445. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  25446. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  25447. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  25448. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  25449. *
  25450. * const extrudeSettings = {
  25451. * depth: 8,
  25452. * bevelEnabled: true,
  25453. * bevelSegments: 2,
  25454. * steps: 2,
  25455. * bevelSize: 1,
  25456. * bevelThickness: 1
  25457. * };
  25458. *
  25459. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  25460. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  25461. * ```
  25462. *
  25463. * @augments Path
  25464. */
  25465. class Shape extends Path {
  25466. /**
  25467. * Constructs a new shape.
  25468. *
  25469. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25470. */
  25471. constructor( points ) {
  25472. super( points );
  25473. /**
  25474. * The UUID of the shape.
  25475. *
  25476. * @type {string}
  25477. * @readonly
  25478. */
  25479. this.uuid = generateUUID();
  25480. this.type = 'Shape';
  25481. /**
  25482. * Defines the holes in the shape. Hole definitions must use the
  25483. * opposite winding order (CW/CCW) than the outer shape.
  25484. *
  25485. * @type {Array<Path>}
  25486. * @readonly
  25487. */
  25488. this.holes = [];
  25489. }
  25490. /**
  25491. * Returns an array representing each contour of the holes
  25492. * as a list of 2D points.
  25493. *
  25494. * @param {number} divisions - The fineness of the result.
  25495. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25496. */
  25497. getPointsHoles( divisions ) {
  25498. const holesPts = [];
  25499. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25500. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25501. }
  25502. return holesPts;
  25503. }
  25504. // get points of shape and holes (keypoints based on segments parameter)
  25505. /**
  25506. * Returns an object that holds contour data for the shape and its holes as
  25507. * arrays of 2D points.
  25508. *
  25509. * @param {number} divisions - The fineness of the result.
  25510. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25511. */
  25512. extractPoints( divisions ) {
  25513. return {
  25514. shape: this.getPoints( divisions ),
  25515. holes: this.getPointsHoles( divisions )
  25516. };
  25517. }
  25518. copy( source ) {
  25519. super.copy( source );
  25520. this.holes = [];
  25521. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25522. const hole = source.holes[ i ];
  25523. this.holes.push( hole.clone() );
  25524. }
  25525. return this;
  25526. }
  25527. toJSON() {
  25528. const data = super.toJSON();
  25529. data.uuid = this.uuid;
  25530. data.holes = [];
  25531. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25532. const hole = this.holes[ i ];
  25533. data.holes.push( hole.toJSON() );
  25534. }
  25535. return data;
  25536. }
  25537. fromJSON( json ) {
  25538. super.fromJSON( json );
  25539. this.uuid = json.uuid;
  25540. this.holes = [];
  25541. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25542. const hole = json.holes[ i ];
  25543. this.holes.push( new Path().fromJSON( hole ) );
  25544. }
  25545. return this;
  25546. }
  25547. }
  25548. /* eslint-disable */
  25549. // copy of mapbox/earcut version 3.0.2
  25550. // https://github.com/mapbox/earcut/tree/v3.0.2
  25551. function earcut(data, holeIndices, dim = 2) {
  25552. const hasHoles = holeIndices && holeIndices.length;
  25553. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25554. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25555. const triangles = [];
  25556. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25557. let minX, minY, invSize;
  25558. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25559. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25560. if (data.length > 80 * dim) {
  25561. minX = data[0];
  25562. minY = data[1];
  25563. let maxX = minX;
  25564. let maxY = minY;
  25565. for (let i = dim; i < outerLen; i += dim) {
  25566. const x = data[i];
  25567. const y = data[i + 1];
  25568. if (x < minX) minX = x;
  25569. if (y < minY) minY = y;
  25570. if (x > maxX) maxX = x;
  25571. if (y > maxY) maxY = y;
  25572. }
  25573. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25574. invSize = Math.max(maxX - minX, maxY - minY);
  25575. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25576. }
  25577. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25578. return triangles;
  25579. }
  25580. // create a circular doubly linked list from polygon points in the specified winding order
  25581. function linkedList(data, start, end, dim, clockwise) {
  25582. let last;
  25583. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25584. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25585. } else {
  25586. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25587. }
  25588. if (last && equals(last, last.next)) {
  25589. removeNode(last);
  25590. last = last.next;
  25591. }
  25592. return last;
  25593. }
  25594. // eliminate colinear or duplicate points
  25595. function filterPoints(start, end) {
  25596. if (!start) return start;
  25597. if (!end) end = start;
  25598. let p = start,
  25599. again;
  25600. do {
  25601. again = false;
  25602. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25603. removeNode(p);
  25604. p = end = p.prev;
  25605. if (p === p.next) break;
  25606. again = true;
  25607. } else {
  25608. p = p.next;
  25609. }
  25610. } while (again || p !== end);
  25611. return end;
  25612. }
  25613. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25614. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25615. if (!ear) return;
  25616. // interlink polygon nodes in z-order
  25617. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25618. let stop = ear;
  25619. // iterate through ears, slicing them one by one
  25620. while (ear.prev !== ear.next) {
  25621. const prev = ear.prev;
  25622. const next = ear.next;
  25623. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25624. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25625. removeNode(ear);
  25626. // skipping the next vertex leads to less sliver triangles
  25627. ear = next.next;
  25628. stop = next.next;
  25629. continue;
  25630. }
  25631. ear = next;
  25632. // if we looped through the whole remaining polygon and can't find any more ears
  25633. if (ear === stop) {
  25634. // try filtering points and slicing again
  25635. if (!pass) {
  25636. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25637. // if this didn't work, try curing all small self-intersections locally
  25638. } else if (pass === 1) {
  25639. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25640. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25641. // as a last resort, try splitting the remaining polygon into two
  25642. } else if (pass === 2) {
  25643. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25644. }
  25645. break;
  25646. }
  25647. }
  25648. }
  25649. // check whether a polygon node forms a valid ear with adjacent nodes
  25650. function isEar(ear) {
  25651. const a = ear.prev,
  25652. b = ear,
  25653. c = ear.next;
  25654. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25655. // now make sure we don't have other points inside the potential ear
  25656. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25657. // triangle bbox
  25658. const x0 = Math.min(ax, bx, cx),
  25659. y0 = Math.min(ay, by, cy),
  25660. x1 = Math.max(ax, bx, cx),
  25661. y1 = Math.max(ay, by, cy);
  25662. let p = c.next;
  25663. while (p !== a) {
  25664. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25665. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25666. area(p.prev, p, p.next) >= 0) return false;
  25667. p = p.next;
  25668. }
  25669. return true;
  25670. }
  25671. function isEarHashed(ear, minX, minY, invSize) {
  25672. const a = ear.prev,
  25673. b = ear,
  25674. c = ear.next;
  25675. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25676. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25677. // triangle bbox
  25678. const x0 = Math.min(ax, bx, cx),
  25679. y0 = Math.min(ay, by, cy),
  25680. x1 = Math.max(ax, bx, cx),
  25681. y1 = Math.max(ay, by, cy);
  25682. // z-order range for the current triangle bbox;
  25683. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25684. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25685. let p = ear.prevZ,
  25686. n = ear.nextZ;
  25687. // look for points inside the triangle in both directions
  25688. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25689. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25690. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25691. p = p.prevZ;
  25692. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25693. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25694. n = n.nextZ;
  25695. }
  25696. // look for remaining points in decreasing z-order
  25697. while (p && p.z >= minZ) {
  25698. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25699. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25700. p = p.prevZ;
  25701. }
  25702. // look for remaining points in increasing z-order
  25703. while (n && n.z <= maxZ) {
  25704. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25705. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25706. n = n.nextZ;
  25707. }
  25708. return true;
  25709. }
  25710. // go through all polygon nodes and cure small local self-intersections
  25711. function cureLocalIntersections(start, triangles) {
  25712. let p = start;
  25713. do {
  25714. const a = p.prev,
  25715. b = p.next.next;
  25716. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25717. triangles.push(a.i, p.i, b.i);
  25718. // remove two nodes involved
  25719. removeNode(p);
  25720. removeNode(p.next);
  25721. p = start = b;
  25722. }
  25723. p = p.next;
  25724. } while (p !== start);
  25725. return filterPoints(p);
  25726. }
  25727. // try splitting polygon into two and triangulate them independently
  25728. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25729. // look for a valid diagonal that divides the polygon into two
  25730. let a = start;
  25731. do {
  25732. let b = a.next.next;
  25733. while (b !== a.prev) {
  25734. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25735. // split the polygon in two by the diagonal
  25736. let c = splitPolygon(a, b);
  25737. // filter colinear points around the cuts
  25738. a = filterPoints(a, a.next);
  25739. c = filterPoints(c, c.next);
  25740. // run earcut on each half
  25741. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25742. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25743. return;
  25744. }
  25745. b = b.next;
  25746. }
  25747. a = a.next;
  25748. } while (a !== start);
  25749. }
  25750. // link every hole into the outer loop, producing a single-ring polygon without holes
  25751. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25752. const queue = [];
  25753. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25754. const start = holeIndices[i] * dim;
  25755. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25756. const list = linkedList(data, start, end, dim, false);
  25757. if (list === list.next) list.steiner = true;
  25758. queue.push(getLeftmost(list));
  25759. }
  25760. queue.sort(compareXYSlope);
  25761. // process holes from left to right
  25762. for (let i = 0; i < queue.length; i++) {
  25763. outerNode = eliminateHole(queue[i], outerNode);
  25764. }
  25765. return outerNode;
  25766. }
  25767. function compareXYSlope(a, b) {
  25768. let result = a.x - b.x;
  25769. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25770. // the bridge to the outer shell is always the point that they meet at.
  25771. if (result === 0) {
  25772. result = a.y - b.y;
  25773. if (result === 0) {
  25774. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25775. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25776. result = aSlope - bSlope;
  25777. }
  25778. }
  25779. return result;
  25780. }
  25781. // find a bridge between vertices that connects hole with an outer ring and link it
  25782. function eliminateHole(hole, outerNode) {
  25783. const bridge = findHoleBridge(hole, outerNode);
  25784. if (!bridge) {
  25785. return outerNode;
  25786. }
  25787. const bridgeReverse = splitPolygon(bridge, hole);
  25788. // filter collinear points around the cuts
  25789. filterPoints(bridgeReverse, bridgeReverse.next);
  25790. return filterPoints(bridge, bridge.next);
  25791. }
  25792. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25793. function findHoleBridge(hole, outerNode) {
  25794. let p = outerNode;
  25795. const hx = hole.x;
  25796. const hy = hole.y;
  25797. let qx = -Infinity;
  25798. let m;
  25799. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25800. // segment's endpoint with lesser x will be potential connection point
  25801. // unless they intersect at a vertex, then choose the vertex
  25802. if (equals(hole, p)) return p;
  25803. do {
  25804. if (equals(hole, p.next)) return p.next;
  25805. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25806. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25807. if (x <= hx && x > qx) {
  25808. qx = x;
  25809. m = p.x < p.next.x ? p : p.next;
  25810. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25811. }
  25812. }
  25813. p = p.next;
  25814. } while (p !== outerNode);
  25815. if (!m) return null;
  25816. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25817. // if there are no points found, we have a valid connection;
  25818. // otherwise choose the point of the minimum angle with the ray as connection point
  25819. const stop = m;
  25820. const mx = m.x;
  25821. const my = m.y;
  25822. let tanMin = Infinity;
  25823. p = m;
  25824. do {
  25825. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25826. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25827. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25828. if (locallyInside(p, hole) &&
  25829. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25830. m = p;
  25831. tanMin = tan;
  25832. }
  25833. }
  25834. p = p.next;
  25835. } while (p !== stop);
  25836. return m;
  25837. }
  25838. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25839. function sectorContainsSector(m, p) {
  25840. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25841. }
  25842. // interlink polygon nodes in z-order
  25843. function indexCurve(start, minX, minY, invSize) {
  25844. let p = start;
  25845. do {
  25846. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25847. p.prevZ = p.prev;
  25848. p.nextZ = p.next;
  25849. p = p.next;
  25850. } while (p !== start);
  25851. p.prevZ.nextZ = null;
  25852. p.prevZ = null;
  25853. sortLinked(p);
  25854. }
  25855. // Simon Tatham's linked list merge sort algorithm
  25856. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25857. function sortLinked(list) {
  25858. let numMerges;
  25859. let inSize = 1;
  25860. do {
  25861. let p = list;
  25862. let e;
  25863. list = null;
  25864. let tail = null;
  25865. numMerges = 0;
  25866. while (p) {
  25867. numMerges++;
  25868. let q = p;
  25869. let pSize = 0;
  25870. for (let i = 0; i < inSize; i++) {
  25871. pSize++;
  25872. q = q.nextZ;
  25873. if (!q) break;
  25874. }
  25875. let qSize = inSize;
  25876. while (pSize > 0 || (qSize > 0 && q)) {
  25877. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25878. e = p;
  25879. p = p.nextZ;
  25880. pSize--;
  25881. } else {
  25882. e = q;
  25883. q = q.nextZ;
  25884. qSize--;
  25885. }
  25886. if (tail) tail.nextZ = e;
  25887. else list = e;
  25888. e.prevZ = tail;
  25889. tail = e;
  25890. }
  25891. p = q;
  25892. }
  25893. tail.nextZ = null;
  25894. inSize *= 2;
  25895. } while (numMerges > 1);
  25896. return list;
  25897. }
  25898. // z-order of a point given coords and inverse of the longer side of data bbox
  25899. function zOrder(x, y, minX, minY, invSize) {
  25900. // coords are transformed into non-negative 15-bit integer range
  25901. x = (x - minX) * invSize | 0;
  25902. y = (y - minY) * invSize | 0;
  25903. x = (x | (x << 8)) & 0x00FF00FF;
  25904. x = (x | (x << 4)) & 0x0F0F0F0F;
  25905. x = (x | (x << 2)) & 0x33333333;
  25906. x = (x | (x << 1)) & 0x55555555;
  25907. y = (y | (y << 8)) & 0x00FF00FF;
  25908. y = (y | (y << 4)) & 0x0F0F0F0F;
  25909. y = (y | (y << 2)) & 0x33333333;
  25910. y = (y | (y << 1)) & 0x55555555;
  25911. return x | (y << 1);
  25912. }
  25913. // find the leftmost node of a polygon ring
  25914. function getLeftmost(start) {
  25915. let p = start,
  25916. leftmost = start;
  25917. do {
  25918. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25919. p = p.next;
  25920. } while (p !== start);
  25921. return leftmost;
  25922. }
  25923. // check if a point lies within a convex triangle
  25924. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25925. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25926. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25927. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25928. }
  25929. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25930. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25931. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25932. }
  25933. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25934. function isValidDiagonal(a, b) {
  25935. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25936. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25937. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25938. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25939. }
  25940. // signed area of a triangle
  25941. function area(p, q, r) {
  25942. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25943. }
  25944. // check if two points are equal
  25945. function equals(p1, p2) {
  25946. return p1.x === p2.x && p1.y === p2.y;
  25947. }
  25948. // check if two segments intersect
  25949. function intersects(p1, q1, p2, q2) {
  25950. const o1 = sign(area(p1, q1, p2));
  25951. const o2 = sign(area(p1, q1, q2));
  25952. const o3 = sign(area(p2, q2, p1));
  25953. const o4 = sign(area(p2, q2, q1));
  25954. if (o1 !== o2 && o3 !== o4) return true; // general case
  25955. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25956. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25957. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25958. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25959. return false;
  25960. }
  25961. // for collinear points p, q, r, check if point q lies on segment pr
  25962. function onSegment(p, q, r) {
  25963. 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);
  25964. }
  25965. function sign(num) {
  25966. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25967. }
  25968. // check if a polygon diagonal intersects any polygon segments
  25969. function intersectsPolygon(a, b) {
  25970. let p = a;
  25971. do {
  25972. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25973. intersects(p, p.next, a, b)) return true;
  25974. p = p.next;
  25975. } while (p !== a);
  25976. return false;
  25977. }
  25978. // check if a polygon diagonal is locally inside the polygon
  25979. function locallyInside(a, b) {
  25980. return area(a.prev, a, a.next) < 0 ?
  25981. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25982. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25983. }
  25984. // check if the middle point of a polygon diagonal is inside the polygon
  25985. function middleInside(a, b) {
  25986. let p = a;
  25987. let inside = false;
  25988. const px = (a.x + b.x) / 2;
  25989. const py = (a.y + b.y) / 2;
  25990. do {
  25991. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25992. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25993. inside = !inside;
  25994. p = p.next;
  25995. } while (p !== a);
  25996. return inside;
  25997. }
  25998. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25999. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  26000. function splitPolygon(a, b) {
  26001. const a2 = createNode(a.i, a.x, a.y),
  26002. b2 = createNode(b.i, b.x, b.y),
  26003. an = a.next,
  26004. bp = b.prev;
  26005. a.next = b;
  26006. b.prev = a;
  26007. a2.next = an;
  26008. an.prev = a2;
  26009. b2.next = a2;
  26010. a2.prev = b2;
  26011. bp.next = b2;
  26012. b2.prev = bp;
  26013. return b2;
  26014. }
  26015. // create a node and optionally link it with previous one (in a circular doubly linked list)
  26016. function insertNode(i, x, y, last) {
  26017. const p = createNode(i, x, y);
  26018. if (!last) {
  26019. p.prev = p;
  26020. p.next = p;
  26021. } else {
  26022. p.next = last.next;
  26023. p.prev = last;
  26024. last.next.prev = p;
  26025. last.next = p;
  26026. }
  26027. return p;
  26028. }
  26029. function removeNode(p) {
  26030. p.next.prev = p.prev;
  26031. p.prev.next = p.next;
  26032. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  26033. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  26034. }
  26035. function createNode(i, x, y) {
  26036. return {
  26037. i, // vertex index in coordinates array
  26038. x, y, // vertex coordinates
  26039. prev: null, // previous and next vertex nodes in a polygon ring
  26040. next: null,
  26041. z: 0, // z-order curve value
  26042. prevZ: null, // previous and next nodes in z-order
  26043. nextZ: null,
  26044. steiner: false // indicates whether this is a steiner point
  26045. };
  26046. }
  26047. function signedArea(data, start, end, dim) {
  26048. let sum = 0;
  26049. for (let i = start, j = end - dim; i < end; i += dim) {
  26050. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  26051. j = i;
  26052. }
  26053. return sum;
  26054. }
  26055. /**
  26056. * An implementation of the earcut polygon triangulation algorithm.
  26057. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  26058. *
  26059. * @see https://github.com/mapbox/earcut
  26060. */
  26061. class Earcut {
  26062. /**
  26063. * Triangulates the given shape definition by returning an array of triangles.
  26064. *
  26065. * @param {Array<number>} data - An array with 2D points.
  26066. * @param {Array<number>} holeIndices - An array with indices defining holes.
  26067. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  26068. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  26069. * representing vertex indices.
  26070. */
  26071. static triangulate( data, holeIndices, dim = 2 ) {
  26072. return earcut( data, holeIndices, dim );
  26073. }
  26074. }
  26075. /**
  26076. * A class containing utility functions for shapes.
  26077. *
  26078. * @hideconstructor
  26079. */
  26080. class ShapeUtils {
  26081. /**
  26082. * Calculate area of a ( 2D ) contour polygon.
  26083. *
  26084. * @param {Array<Vector2>} contour - An array of 2D points.
  26085. * @return {number} The area.
  26086. */
  26087. static area( contour ) {
  26088. const n = contour.length;
  26089. let a = 0.0;
  26090. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  26091. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  26092. }
  26093. return a * 0.5;
  26094. }
  26095. /**
  26096. * Returns `true` if the given contour uses a clockwise winding order.
  26097. *
  26098. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  26099. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  26100. */
  26101. static isClockWise( pts ) {
  26102. return ShapeUtils.area( pts ) < 0;
  26103. }
  26104. /**
  26105. * Triangulates the given shape definition.
  26106. *
  26107. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  26108. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  26109. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  26110. */
  26111. static triangulateShape( contour, holes ) {
  26112. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  26113. const holeIndices = []; // array of hole indices
  26114. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  26115. removeDupEndPts( contour );
  26116. addContour( vertices, contour );
  26117. //
  26118. let holeIndex = contour.length;
  26119. holes.forEach( removeDupEndPts );
  26120. for ( let i = 0; i < holes.length; i ++ ) {
  26121. holeIndices.push( holeIndex );
  26122. holeIndex += holes[ i ].length;
  26123. addContour( vertices, holes[ i ] );
  26124. }
  26125. //
  26126. const triangles = Earcut.triangulate( vertices, holeIndices );
  26127. //
  26128. for ( let i = 0; i < triangles.length; i += 3 ) {
  26129. faces.push( triangles.slice( i, i + 3 ) );
  26130. }
  26131. return faces;
  26132. }
  26133. }
  26134. function removeDupEndPts( points ) {
  26135. const l = points.length;
  26136. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  26137. points.pop();
  26138. }
  26139. }
  26140. function addContour( vertices, contour ) {
  26141. for ( let i = 0; i < contour.length; i ++ ) {
  26142. vertices.push( contour[ i ].x );
  26143. vertices.push( contour[ i ].y );
  26144. }
  26145. }
  26146. /**
  26147. * Creates extruded geometry from a path shape.
  26148. *
  26149. * ```js
  26150. * const length = 12, width = 8;
  26151. *
  26152. * const shape = new THREE.Shape();
  26153. * shape.moveTo( 0,0 );
  26154. * shape.lineTo( 0, width );
  26155. * shape.lineTo( length, width );
  26156. * shape.lineTo( length, 0 );
  26157. * shape.lineTo( 0, 0 );
  26158. *
  26159. * const geometry = new THREE.ExtrudeGeometry( shape );
  26160. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  26161. * const mesh = new THREE.Mesh( geometry, material ) ;
  26162. * scene.add( mesh );
  26163. * ```
  26164. *
  26165. * @augments BufferGeometry
  26166. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  26167. */
  26168. class ExtrudeGeometry extends BufferGeometry {
  26169. /**
  26170. * Constructs a new extrude geometry.
  26171. *
  26172. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26173. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  26174. */
  26175. 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 = {} ) {
  26176. super();
  26177. this.type = 'ExtrudeGeometry';
  26178. /**
  26179. * Holds the constructor parameters that have been
  26180. * used to generate the geometry. Any modification
  26181. * after instantiation does not change the geometry.
  26182. *
  26183. * @type {Object}
  26184. */
  26185. this.parameters = {
  26186. shapes: shapes,
  26187. options: options
  26188. };
  26189. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  26190. const scope = this;
  26191. const verticesArray = [];
  26192. const uvArray = [];
  26193. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26194. const shape = shapes[ i ];
  26195. addShape( shape );
  26196. }
  26197. // build geometry
  26198. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  26199. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  26200. this.computeVertexNormals();
  26201. // functions
  26202. function addShape( shape ) {
  26203. const placeholder = [];
  26204. // options
  26205. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  26206. const steps = options.steps !== undefined ? options.steps : 1;
  26207. const depth = options.depth !== undefined ? options.depth : 1;
  26208. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  26209. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  26210. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  26211. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  26212. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  26213. const extrudePath = options.extrudePath;
  26214. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  26215. //
  26216. let extrudePts, extrudeByPath = false;
  26217. let splineTube, binormal, normal, position2;
  26218. if ( extrudePath ) {
  26219. extrudePts = extrudePath.getSpacedPoints( steps );
  26220. extrudeByPath = true;
  26221. bevelEnabled = false; // bevels not supported for path extrusion
  26222. // SETUP TNB variables
  26223. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  26224. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  26225. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  26226. binormal = new Vector3();
  26227. normal = new Vector3();
  26228. position2 = new Vector3();
  26229. }
  26230. // Safeguards if bevels are not enabled
  26231. if ( ! bevelEnabled ) {
  26232. bevelSegments = 0;
  26233. bevelThickness = 0;
  26234. bevelSize = 0;
  26235. bevelOffset = 0;
  26236. }
  26237. // Variables initialization
  26238. const shapePoints = shape.extractPoints( curveSegments );
  26239. let vertices = shapePoints.shape;
  26240. const holes = shapePoints.holes;
  26241. const reverse = ! ShapeUtils.isClockWise( vertices );
  26242. if ( reverse ) {
  26243. vertices = vertices.reverse();
  26244. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  26245. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26246. const ahole = holes[ h ];
  26247. if ( ShapeUtils.isClockWise( ahole ) ) {
  26248. holes[ h ] = ahole.reverse();
  26249. }
  26250. }
  26251. }
  26252. /**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.
  26253. * @param {Array<Vector2>} points
  26254. */
  26255. function mergeOverlappingPoints( points ) {
  26256. const THRESHOLD = 1e-10;
  26257. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  26258. let prevPos = points[ 0 ];
  26259. for ( let i = 1; i <= points.length; i ++ ) {
  26260. const currentIndex = i % points.length;
  26261. const currentPos = points[ currentIndex ];
  26262. const dx = currentPos.x - prevPos.x;
  26263. const dy = currentPos.y - prevPos.y;
  26264. const distSq = dx * dx + dy * dy;
  26265. const scalingFactorSqrt = Math.max(
  26266. Math.abs( currentPos.x ),
  26267. Math.abs( currentPos.y ),
  26268. Math.abs( prevPos.x ),
  26269. Math.abs( prevPos.y )
  26270. );
  26271. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  26272. if ( distSq <= thresholdSqScaled ) {
  26273. points.splice( currentIndex, 1 );
  26274. i --;
  26275. continue;
  26276. }
  26277. prevPos = currentPos;
  26278. }
  26279. }
  26280. mergeOverlappingPoints( vertices );
  26281. holes.forEach( mergeOverlappingPoints );
  26282. const numHoles = holes.length;
  26283. /* Vertices */
  26284. const contour = vertices; // vertices has all points but contour has only points of circumference
  26285. for ( let h = 0; h < numHoles; h ++ ) {
  26286. const ahole = holes[ h ];
  26287. vertices = vertices.concat( ahole );
  26288. }
  26289. function scalePt2( pt, vec, size ) {
  26290. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  26291. return pt.clone().addScaledVector( vec, size );
  26292. }
  26293. const vlen = vertices.length;
  26294. // Find directions for point movement
  26295. function getBevelVec( inPt, inPrev, inNext ) {
  26296. // computes for inPt the corresponding point inPt' on a new contour
  26297. // shifted by 1 unit (length of normalized vector) to the left
  26298. // if we walk along contour clockwise, this new contour is outside the old one
  26299. //
  26300. // inPt' is the intersection of the two lines parallel to the two
  26301. // adjacent edges of inPt at a distance of 1 unit on the left side.
  26302. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  26303. // good reading for geometry algorithms (here: line-line intersection)
  26304. // http://geomalgorithms.com/a05-_intersect-1.html
  26305. const v_prev_x = inPt.x - inPrev.x,
  26306. v_prev_y = inPt.y - inPrev.y;
  26307. const v_next_x = inNext.x - inPt.x,
  26308. v_next_y = inNext.y - inPt.y;
  26309. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  26310. // check for collinear edges
  26311. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26312. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  26313. // not collinear
  26314. // length of vectors for normalizing
  26315. const v_prev_len = Math.sqrt( v_prev_lensq );
  26316. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  26317. // shift adjacent points by unit vectors to the left
  26318. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  26319. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  26320. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  26321. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  26322. // scaling factor for v_prev to intersection point
  26323. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  26324. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  26325. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26326. // vector from inPt to intersection point
  26327. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  26328. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  26329. // Don't normalize!, otherwise sharp corners become ugly
  26330. // but prevent crazy spikes
  26331. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  26332. if ( v_trans_lensq <= 2 ) {
  26333. return new Vector2( v_trans_x, v_trans_y );
  26334. } else {
  26335. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  26336. }
  26337. } else {
  26338. // handle special case of collinear edges
  26339. let direction_eq = false; // assumes: opposite
  26340. if ( v_prev_x > Number.EPSILON ) {
  26341. if ( v_next_x > Number.EPSILON ) {
  26342. direction_eq = true;
  26343. }
  26344. } else {
  26345. if ( v_prev_x < - Number.EPSILON ) {
  26346. if ( v_next_x < - Number.EPSILON ) {
  26347. direction_eq = true;
  26348. }
  26349. } else {
  26350. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  26351. direction_eq = true;
  26352. }
  26353. }
  26354. }
  26355. if ( direction_eq ) {
  26356. // log("Warning: lines are a straight sequence");
  26357. v_trans_x = - v_prev_y;
  26358. v_trans_y = v_prev_x;
  26359. shrink_by = Math.sqrt( v_prev_lensq );
  26360. } else {
  26361. // log("Warning: lines are a straight spike");
  26362. v_trans_x = v_prev_x;
  26363. v_trans_y = v_prev_y;
  26364. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  26365. }
  26366. }
  26367. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  26368. }
  26369. const contourMovements = [];
  26370. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26371. if ( j === il ) j = 0;
  26372. if ( k === il ) k = 0;
  26373. // (j)---(i)---(k)
  26374. // log('i,j,k', i, j , k)
  26375. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  26376. }
  26377. const holesMovements = [];
  26378. let oneHoleMovements, verticesMovements = contourMovements.concat();
  26379. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26380. const ahole = holes[ h ];
  26381. oneHoleMovements = [];
  26382. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26383. if ( j === il ) j = 0;
  26384. if ( k === il ) k = 0;
  26385. // (j)---(i)---(k)
  26386. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  26387. }
  26388. holesMovements.push( oneHoleMovements );
  26389. verticesMovements = verticesMovements.concat( oneHoleMovements );
  26390. }
  26391. let faces;
  26392. if ( bevelSegments === 0 ) {
  26393. faces = ShapeUtils.triangulateShape( contour, holes );
  26394. } else {
  26395. const contractedContourVertices = [];
  26396. const expandedHoleVertices = [];
  26397. // Loop bevelSegments, 1 for the front, 1 for the back
  26398. for ( let b = 0; b < bevelSegments; b ++ ) {
  26399. //for ( b = bevelSegments; b > 0; b -- ) {
  26400. const t = b / bevelSegments;
  26401. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26402. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26403. // contract shape
  26404. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26405. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26406. v( vert.x, vert.y, - z );
  26407. if ( t === 0 ) contractedContourVertices.push( vert );
  26408. }
  26409. // expand holes
  26410. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26411. const ahole = holes[ h ];
  26412. oneHoleMovements = holesMovements[ h ];
  26413. const oneHoleVertices = [];
  26414. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26415. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26416. v( vert.x, vert.y, - z );
  26417. if ( t === 0 ) oneHoleVertices.push( vert );
  26418. }
  26419. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  26420. }
  26421. }
  26422. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  26423. }
  26424. const flen = faces.length;
  26425. const bs = bevelSize + bevelOffset;
  26426. // Back facing vertices
  26427. for ( let i = 0; i < vlen; i ++ ) {
  26428. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26429. if ( ! extrudeByPath ) {
  26430. v( vert.x, vert.y, 0 );
  26431. } else {
  26432. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  26433. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  26434. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  26435. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  26436. v( position2.x, position2.y, position2.z );
  26437. }
  26438. }
  26439. // Add stepped vertices...
  26440. // Including front facing vertices
  26441. for ( let s = 1; s <= steps; s ++ ) {
  26442. for ( let i = 0; i < vlen; i ++ ) {
  26443. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26444. if ( ! extrudeByPath ) {
  26445. v( vert.x, vert.y, depth / steps * s );
  26446. } else {
  26447. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  26448. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  26449. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  26450. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  26451. v( position2.x, position2.y, position2.z );
  26452. }
  26453. }
  26454. }
  26455. // Add bevel segments planes
  26456. //for ( b = 1; b <= bevelSegments; b ++ ) {
  26457. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  26458. const t = b / bevelSegments;
  26459. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26460. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26461. // contract shape
  26462. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26463. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26464. v( vert.x, vert.y, depth + z );
  26465. }
  26466. // expand holes
  26467. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26468. const ahole = holes[ h ];
  26469. oneHoleMovements = holesMovements[ h ];
  26470. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26471. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26472. if ( ! extrudeByPath ) {
  26473. v( vert.x, vert.y, depth + z );
  26474. } else {
  26475. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  26476. }
  26477. }
  26478. }
  26479. }
  26480. /* Faces */
  26481. // Top and bottom faces
  26482. buildLidFaces();
  26483. // Sides faces
  26484. buildSideFaces();
  26485. ///// Internal functions
  26486. function buildLidFaces() {
  26487. const start = verticesArray.length / 3;
  26488. if ( bevelEnabled ) {
  26489. let layer = 0; // steps + 1
  26490. let offset = vlen * layer;
  26491. // Bottom faces
  26492. for ( let i = 0; i < flen; i ++ ) {
  26493. const face = faces[ i ];
  26494. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26495. }
  26496. layer = steps + bevelSegments * 2;
  26497. offset = vlen * layer;
  26498. // Top faces
  26499. for ( let i = 0; i < flen; i ++ ) {
  26500. const face = faces[ i ];
  26501. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26502. }
  26503. } else {
  26504. // Bottom faces
  26505. for ( let i = 0; i < flen; i ++ ) {
  26506. const face = faces[ i ];
  26507. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26508. }
  26509. // Top faces
  26510. for ( let i = 0; i < flen; i ++ ) {
  26511. const face = faces[ i ];
  26512. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26513. }
  26514. }
  26515. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26516. }
  26517. // Create faces for the z-sides of the shape
  26518. function buildSideFaces() {
  26519. const start = verticesArray.length / 3;
  26520. let layeroffset = 0;
  26521. sidewalls( contour, layeroffset );
  26522. layeroffset += contour.length;
  26523. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26524. const ahole = holes[ h ];
  26525. sidewalls( ahole, layeroffset );
  26526. //, true
  26527. layeroffset += ahole.length;
  26528. }
  26529. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26530. }
  26531. function sidewalls( contour, layeroffset ) {
  26532. let i = contour.length;
  26533. while ( -- i >= 0 ) {
  26534. const j = i;
  26535. let k = i - 1;
  26536. if ( k < 0 ) k = contour.length - 1;
  26537. //log('b', i,j, i-1, k,vertices.length);
  26538. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26539. const slen1 = vlen * s;
  26540. const slen2 = vlen * ( s + 1 );
  26541. const a = layeroffset + j + slen1,
  26542. b = layeroffset + k + slen1,
  26543. c = layeroffset + k + slen2,
  26544. d = layeroffset + j + slen2;
  26545. f4( a, b, c, d );
  26546. }
  26547. }
  26548. }
  26549. function v( x, y, z ) {
  26550. placeholder.push( x );
  26551. placeholder.push( y );
  26552. placeholder.push( z );
  26553. }
  26554. function f3( a, b, c ) {
  26555. addVertex( a );
  26556. addVertex( b );
  26557. addVertex( c );
  26558. const nextIndex = verticesArray.length / 3;
  26559. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26560. addUV( uvs[ 0 ] );
  26561. addUV( uvs[ 1 ] );
  26562. addUV( uvs[ 2 ] );
  26563. }
  26564. function f4( a, b, c, d ) {
  26565. addVertex( a );
  26566. addVertex( b );
  26567. addVertex( d );
  26568. addVertex( b );
  26569. addVertex( c );
  26570. addVertex( d );
  26571. const nextIndex = verticesArray.length / 3;
  26572. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26573. addUV( uvs[ 0 ] );
  26574. addUV( uvs[ 1 ] );
  26575. addUV( uvs[ 3 ] );
  26576. addUV( uvs[ 1 ] );
  26577. addUV( uvs[ 2 ] );
  26578. addUV( uvs[ 3 ] );
  26579. }
  26580. function addVertex( index ) {
  26581. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26582. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26583. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26584. }
  26585. function addUV( vector2 ) {
  26586. uvArray.push( vector2.x );
  26587. uvArray.push( vector2.y );
  26588. }
  26589. }
  26590. }
  26591. copy( source ) {
  26592. super.copy( source );
  26593. this.parameters = Object.assign( {}, source.parameters );
  26594. return this;
  26595. }
  26596. toJSON() {
  26597. const data = super.toJSON();
  26598. const shapes = this.parameters.shapes;
  26599. const options = this.parameters.options;
  26600. return toJSON$1( shapes, options, data );
  26601. }
  26602. /**
  26603. * Factory method for creating an instance of this class from the given
  26604. * JSON object.
  26605. *
  26606. * @param {Object} data - A JSON object representing the serialized geometry.
  26607. * @param {Array<Shape>} shapes - An array of shapes.
  26608. * @return {ExtrudeGeometry} A new instance.
  26609. */
  26610. static fromJSON( data, shapes ) {
  26611. const geometryShapes = [];
  26612. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26613. const shape = shapes[ data.shapes[ j ] ];
  26614. geometryShapes.push( shape );
  26615. }
  26616. const extrudePath = data.options.extrudePath;
  26617. if ( extrudePath !== undefined ) {
  26618. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26619. }
  26620. return new ExtrudeGeometry( geometryShapes, data.options );
  26621. }
  26622. }
  26623. const WorldUVGenerator = {
  26624. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26625. const a_x = vertices[ indexA * 3 ];
  26626. const a_y = vertices[ indexA * 3 + 1 ];
  26627. const b_x = vertices[ indexB * 3 ];
  26628. const b_y = vertices[ indexB * 3 + 1 ];
  26629. const c_x = vertices[ indexC * 3 ];
  26630. const c_y = vertices[ indexC * 3 + 1 ];
  26631. return [
  26632. new Vector2( a_x, a_y ),
  26633. new Vector2( b_x, b_y ),
  26634. new Vector2( c_x, c_y )
  26635. ];
  26636. },
  26637. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26638. const a_x = vertices[ indexA * 3 ];
  26639. const a_y = vertices[ indexA * 3 + 1 ];
  26640. const a_z = vertices[ indexA * 3 + 2 ];
  26641. const b_x = vertices[ indexB * 3 ];
  26642. const b_y = vertices[ indexB * 3 + 1 ];
  26643. const b_z = vertices[ indexB * 3 + 2 ];
  26644. const c_x = vertices[ indexC * 3 ];
  26645. const c_y = vertices[ indexC * 3 + 1 ];
  26646. const c_z = vertices[ indexC * 3 + 2 ];
  26647. const d_x = vertices[ indexD * 3 ];
  26648. const d_y = vertices[ indexD * 3 + 1 ];
  26649. const d_z = vertices[ indexD * 3 + 2 ];
  26650. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26651. return [
  26652. new Vector2( a_x, 1 - a_z ),
  26653. new Vector2( b_x, 1 - b_z ),
  26654. new Vector2( c_x, 1 - c_z ),
  26655. new Vector2( d_x, 1 - d_z )
  26656. ];
  26657. } else {
  26658. return [
  26659. new Vector2( a_y, 1 - a_z ),
  26660. new Vector2( b_y, 1 - b_z ),
  26661. new Vector2( c_y, 1 - c_z ),
  26662. new Vector2( d_y, 1 - d_z )
  26663. ];
  26664. }
  26665. }
  26666. };
  26667. function toJSON$1( shapes, options, data ) {
  26668. data.shapes = [];
  26669. if ( Array.isArray( shapes ) ) {
  26670. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26671. const shape = shapes[ i ];
  26672. data.shapes.push( shape.uuid );
  26673. }
  26674. } else {
  26675. data.shapes.push( shapes.uuid );
  26676. }
  26677. data.options = Object.assign( {}, options );
  26678. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26679. return data;
  26680. }
  26681. /**
  26682. * A geometry class for representing an icosahedron.
  26683. *
  26684. * ```js
  26685. * const geometry = new THREE.IcosahedronGeometry();
  26686. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26687. * const icosahedron = new THREE.Mesh( geometry, material );
  26688. * scene.add( icosahedron );
  26689. * ```
  26690. *
  26691. * @augments PolyhedronGeometry
  26692. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  26693. */
  26694. class IcosahedronGeometry extends PolyhedronGeometry {
  26695. /**
  26696. * Constructs a new icosahedron geometry.
  26697. *
  26698. * @param {number} [radius=1] - Radius of the icosahedron.
  26699. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26700. */
  26701. constructor( radius = 1, detail = 0 ) {
  26702. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26703. const vertices = [
  26704. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26705. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26706. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26707. ];
  26708. const indices = [
  26709. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26710. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26711. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26712. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26713. ];
  26714. super( vertices, indices, radius, detail );
  26715. this.type = 'IcosahedronGeometry';
  26716. /**
  26717. * Holds the constructor parameters that have been
  26718. * used to generate the geometry. Any modification
  26719. * after instantiation does not change the geometry.
  26720. *
  26721. * @type {Object}
  26722. */
  26723. this.parameters = {
  26724. radius: radius,
  26725. detail: detail
  26726. };
  26727. }
  26728. /**
  26729. * Factory method for creating an instance of this class from the given
  26730. * JSON object.
  26731. *
  26732. * @param {Object} data - A JSON object representing the serialized geometry.
  26733. * @return {IcosahedronGeometry} A new instance.
  26734. */
  26735. static fromJSON( data ) {
  26736. return new IcosahedronGeometry( data.radius, data.detail );
  26737. }
  26738. }
  26739. /**
  26740. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26741. *
  26742. * ```js
  26743. * const points = [];
  26744. * for ( let i = 0; i < 10; i ++ ) {
  26745. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26746. * }
  26747. * const geometry = new THREE.LatheGeometry( points );
  26748. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26749. * const lathe = new THREE.Mesh( geometry, material );
  26750. * scene.add( lathe );
  26751. * ```
  26752. *
  26753. * @augments BufferGeometry
  26754. * @demo scenes/geometry-browser.html#LatheGeometry
  26755. */
  26756. class LatheGeometry extends BufferGeometry {
  26757. /**
  26758. * Constructs a new lathe geometry.
  26759. *
  26760. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26761. * must be greater than zero.
  26762. * @param {number} [segments=12] - The number of circumference segments to generate.
  26763. * @param {number} [phiStart=0] - The starting angle in radians.
  26764. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26765. * closed lathe, less than 2PI is a portion.
  26766. */
  26767. 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 ) {
  26768. super();
  26769. this.type = 'LatheGeometry';
  26770. /**
  26771. * Holds the constructor parameters that have been
  26772. * used to generate the geometry. Any modification
  26773. * after instantiation does not change the geometry.
  26774. *
  26775. * @type {Object}
  26776. */
  26777. this.parameters = {
  26778. points: points,
  26779. segments: segments,
  26780. phiStart: phiStart,
  26781. phiLength: phiLength
  26782. };
  26783. segments = Math.floor( segments );
  26784. // clamp phiLength so it's in range of [ 0, 2PI ]
  26785. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26786. // buffers
  26787. const indices = [];
  26788. const vertices = [];
  26789. const uvs = [];
  26790. const initNormals = [];
  26791. const normals = [];
  26792. // helper variables
  26793. const inverseSegments = 1.0 / segments;
  26794. const vertex = new Vector3();
  26795. const uv = new Vector2();
  26796. const normal = new Vector3();
  26797. const curNormal = new Vector3();
  26798. const prevNormal = new Vector3();
  26799. let dx = 0;
  26800. let dy = 0;
  26801. // pre-compute normals for initial "meridian"
  26802. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26803. switch ( j ) {
  26804. case 0: // special handling for 1st vertex on path
  26805. dx = points[ j + 1 ].x - points[ j ].x;
  26806. dy = points[ j + 1 ].y - points[ j ].y;
  26807. normal.x = dy * 1.0;
  26808. normal.y = - dx;
  26809. normal.z = dy * 0.0;
  26810. prevNormal.copy( normal );
  26811. normal.normalize();
  26812. initNormals.push( normal.x, normal.y, normal.z );
  26813. break;
  26814. case ( points.length - 1 ): // special handling for last Vertex on path
  26815. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26816. break;
  26817. default: // default handling for all vertices in between
  26818. dx = points[ j + 1 ].x - points[ j ].x;
  26819. dy = points[ j + 1 ].y - points[ j ].y;
  26820. normal.x = dy * 1.0;
  26821. normal.y = - dx;
  26822. normal.z = dy * 0.0;
  26823. curNormal.copy( normal );
  26824. normal.x += prevNormal.x;
  26825. normal.y += prevNormal.y;
  26826. normal.z += prevNormal.z;
  26827. normal.normalize();
  26828. initNormals.push( normal.x, normal.y, normal.z );
  26829. prevNormal.copy( curNormal );
  26830. }
  26831. }
  26832. // generate vertices, uvs and normals
  26833. for ( let i = 0; i <= segments; i ++ ) {
  26834. const phi = phiStart + i * inverseSegments * phiLength;
  26835. const sin = Math.sin( phi );
  26836. const cos = Math.cos( phi );
  26837. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26838. // vertex
  26839. vertex.x = points[ j ].x * sin;
  26840. vertex.y = points[ j ].y;
  26841. vertex.z = points[ j ].x * cos;
  26842. vertices.push( vertex.x, vertex.y, vertex.z );
  26843. // uv
  26844. uv.x = i / segments;
  26845. uv.y = j / ( points.length - 1 );
  26846. uvs.push( uv.x, uv.y );
  26847. // normal
  26848. const x = initNormals[ 3 * j + 0 ] * sin;
  26849. const y = initNormals[ 3 * j + 1 ];
  26850. const z = initNormals[ 3 * j + 0 ] * cos;
  26851. normals.push( x, y, z );
  26852. }
  26853. }
  26854. // indices
  26855. for ( let i = 0; i < segments; i ++ ) {
  26856. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26857. const base = j + i * points.length;
  26858. const a = base;
  26859. const b = base + points.length;
  26860. const c = base + points.length + 1;
  26861. const d = base + 1;
  26862. // faces
  26863. indices.push( a, b, d );
  26864. indices.push( c, d, b );
  26865. }
  26866. }
  26867. // build geometry
  26868. this.setIndex( indices );
  26869. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26870. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26871. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26872. }
  26873. copy( source ) {
  26874. super.copy( source );
  26875. this.parameters = Object.assign( {}, source.parameters );
  26876. return this;
  26877. }
  26878. /**
  26879. * Factory method for creating an instance of this class from the given
  26880. * JSON object.
  26881. *
  26882. * @param {Object} data - A JSON object representing the serialized geometry.
  26883. * @return {LatheGeometry} A new instance.
  26884. */
  26885. static fromJSON( data ) {
  26886. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26887. }
  26888. }
  26889. /**
  26890. * A geometry class for representing an octahedron.
  26891. *
  26892. * ```js
  26893. * const geometry = new THREE.OctahedronGeometry();
  26894. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26895. * const octahedron = new THREE.Mesh( geometry, material );
  26896. * scene.add( octahedron );
  26897. * ```
  26898. *
  26899. * @augments PolyhedronGeometry
  26900. * @demo scenes/geometry-browser.html#OctahedronGeometry
  26901. */
  26902. class OctahedronGeometry extends PolyhedronGeometry {
  26903. /**
  26904. * Constructs a new octahedron geometry.
  26905. *
  26906. * @param {number} [radius=1] - Radius of the octahedron.
  26907. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26908. */
  26909. constructor( radius = 1, detail = 0 ) {
  26910. const vertices = [
  26911. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26912. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26913. ];
  26914. const indices = [
  26915. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26916. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26917. 1, 3, 4, 1, 4, 2
  26918. ];
  26919. super( vertices, indices, radius, detail );
  26920. this.type = 'OctahedronGeometry';
  26921. /**
  26922. * Holds the constructor parameters that have been
  26923. * used to generate the geometry. Any modification
  26924. * after instantiation does not change the geometry.
  26925. *
  26926. * @type {Object}
  26927. */
  26928. this.parameters = {
  26929. radius: radius,
  26930. detail: detail
  26931. };
  26932. }
  26933. /**
  26934. * Factory method for creating an instance of this class from the given
  26935. * JSON object.
  26936. *
  26937. * @param {Object} data - A JSON object representing the serialized geometry.
  26938. * @return {OctahedronGeometry} A new instance.
  26939. */
  26940. static fromJSON( data ) {
  26941. return new OctahedronGeometry( data.radius, data.detail );
  26942. }
  26943. }
  26944. /**
  26945. * A geometry class for representing a plane.
  26946. *
  26947. * ```js
  26948. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26949. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26950. * const plane = new THREE.Mesh( geometry, material );
  26951. * scene.add( plane );
  26952. * ```
  26953. *
  26954. * @augments BufferGeometry
  26955. * @demo scenes/geometry-browser.html#PlaneGeometry
  26956. */
  26957. class PlaneGeometry extends BufferGeometry {
  26958. /**
  26959. * Constructs a new plane geometry.
  26960. *
  26961. * @param {number} [width=1] - The width along the X axis.
  26962. * @param {number} [height=1] - The height along the Y axis
  26963. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26964. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26965. */
  26966. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26967. super();
  26968. this.type = 'PlaneGeometry';
  26969. /**
  26970. * Holds the constructor parameters that have been
  26971. * used to generate the geometry. Any modification
  26972. * after instantiation does not change the geometry.
  26973. *
  26974. * @type {Object}
  26975. */
  26976. this.parameters = {
  26977. width: width,
  26978. height: height,
  26979. widthSegments: widthSegments,
  26980. heightSegments: heightSegments
  26981. };
  26982. const width_half = width / 2;
  26983. const height_half = height / 2;
  26984. const gridX = Math.floor( widthSegments );
  26985. const gridY = Math.floor( heightSegments );
  26986. const gridX1 = gridX + 1;
  26987. const gridY1 = gridY + 1;
  26988. const segment_width = width / gridX;
  26989. const segment_height = height / gridY;
  26990. //
  26991. const indices = [];
  26992. const vertices = [];
  26993. const normals = [];
  26994. const uvs = [];
  26995. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26996. const y = iy * segment_height - height_half;
  26997. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26998. const x = ix * segment_width - width_half;
  26999. vertices.push( x, - y, 0 );
  27000. normals.push( 0, 0, 1 );
  27001. uvs.push( ix / gridX );
  27002. uvs.push( 1 - ( iy / gridY ) );
  27003. }
  27004. }
  27005. for ( let iy = 0; iy < gridY; iy ++ ) {
  27006. for ( let ix = 0; ix < gridX; ix ++ ) {
  27007. const a = ix + gridX1 * iy;
  27008. const b = ix + gridX1 * ( iy + 1 );
  27009. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  27010. const d = ( ix + 1 ) + gridX1 * iy;
  27011. indices.push( a, b, d );
  27012. indices.push( b, c, d );
  27013. }
  27014. }
  27015. this.setIndex( indices );
  27016. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27017. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27018. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27019. }
  27020. copy( source ) {
  27021. super.copy( source );
  27022. this.parameters = Object.assign( {}, source.parameters );
  27023. return this;
  27024. }
  27025. /**
  27026. * Factory method for creating an instance of this class from the given
  27027. * JSON object.
  27028. *
  27029. * @param {Object} data - A JSON object representing the serialized geometry.
  27030. * @return {PlaneGeometry} A new instance.
  27031. */
  27032. static fromJSON( data ) {
  27033. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  27034. }
  27035. }
  27036. /**
  27037. * A class for generating a two-dimensional ring geometry.
  27038. *
  27039. * ```js
  27040. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  27041. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  27042. * const mesh = new THREE.Mesh( geometry, material );
  27043. * scene.add( mesh );
  27044. * ```
  27045. *
  27046. * @augments BufferGeometry
  27047. * @demo scenes/geometry-browser.html#RingGeometry
  27048. */
  27049. class RingGeometry extends BufferGeometry {
  27050. /**
  27051. * Constructs a new ring geometry.
  27052. *
  27053. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  27054. * @param {number} [outerRadius=1] - The outer radius of the ring.
  27055. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  27056. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  27057. * @param {number} [thetaStart=0] - Starting angle in radians.
  27058. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  27059. */
  27060. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  27061. super();
  27062. this.type = 'RingGeometry';
  27063. /**
  27064. * Holds the constructor parameters that have been
  27065. * used to generate the geometry. Any modification
  27066. * after instantiation does not change the geometry.
  27067. *
  27068. * @type {Object}
  27069. */
  27070. this.parameters = {
  27071. innerRadius: innerRadius,
  27072. outerRadius: outerRadius,
  27073. thetaSegments: thetaSegments,
  27074. phiSegments: phiSegments,
  27075. thetaStart: thetaStart,
  27076. thetaLength: thetaLength
  27077. };
  27078. thetaSegments = Math.max( 3, thetaSegments );
  27079. phiSegments = Math.max( 1, phiSegments );
  27080. // buffers
  27081. const indices = [];
  27082. const vertices = [];
  27083. const normals = [];
  27084. const uvs = [];
  27085. // some helper variables
  27086. let radius = innerRadius;
  27087. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  27088. const vertex = new Vector3();
  27089. const uv = new Vector2();
  27090. // generate vertices, normals and uvs
  27091. for ( let j = 0; j <= phiSegments; j ++ ) {
  27092. for ( let i = 0; i <= thetaSegments; i ++ ) {
  27093. // values are generate from the inside of the ring to the outside
  27094. const segment = thetaStart + i / thetaSegments * thetaLength;
  27095. // vertex
  27096. vertex.x = radius * Math.cos( segment );
  27097. vertex.y = radius * Math.sin( segment );
  27098. vertices.push( vertex.x, vertex.y, vertex.z );
  27099. // normal
  27100. normals.push( 0, 0, 1 );
  27101. // uv
  27102. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  27103. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  27104. uvs.push( uv.x, uv.y );
  27105. }
  27106. // increase the radius for next row of vertices
  27107. radius += radiusStep;
  27108. }
  27109. // indices
  27110. for ( let j = 0; j < phiSegments; j ++ ) {
  27111. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  27112. for ( let i = 0; i < thetaSegments; i ++ ) {
  27113. const segment = i + thetaSegmentLevel;
  27114. const a = segment;
  27115. const b = segment + thetaSegments + 1;
  27116. const c = segment + thetaSegments + 2;
  27117. const d = segment + 1;
  27118. // faces
  27119. indices.push( a, b, d );
  27120. indices.push( b, c, d );
  27121. }
  27122. }
  27123. // build geometry
  27124. this.setIndex( indices );
  27125. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27126. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27127. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27128. }
  27129. copy( source ) {
  27130. super.copy( source );
  27131. this.parameters = Object.assign( {}, source.parameters );
  27132. return this;
  27133. }
  27134. /**
  27135. * Factory method for creating an instance of this class from the given
  27136. * JSON object.
  27137. *
  27138. * @param {Object} data - A JSON object representing the serialized geometry.
  27139. * @return {RingGeometry} A new instance.
  27140. */
  27141. static fromJSON( data ) {
  27142. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  27143. }
  27144. }
  27145. /**
  27146. * Creates an one-sided polygonal geometry from one or more path shapes.
  27147. *
  27148. * ```js
  27149. * const arcShape = new THREE.Shape()
  27150. * .moveTo( 5, 1 )
  27151. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  27152. *
  27153. * const geometry = new THREE.ShapeGeometry( arcShape );
  27154. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  27155. * const mesh = new THREE.Mesh( geometry, material ) ;
  27156. * scene.add( mesh );
  27157. * ```
  27158. *
  27159. * @augments BufferGeometry
  27160. * @demo scenes/geometry-browser.html#ShapeGeometry
  27161. */
  27162. class ShapeGeometry extends BufferGeometry {
  27163. /**
  27164. * Constructs a new shape geometry.
  27165. *
  27166. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  27167. * @param {number} [curveSegments=12] - Number of segments per shape.
  27168. */
  27169. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  27170. super();
  27171. this.type = 'ShapeGeometry';
  27172. /**
  27173. * Holds the constructor parameters that have been
  27174. * used to generate the geometry. Any modification
  27175. * after instantiation does not change the geometry.
  27176. *
  27177. * @type {Object}
  27178. */
  27179. this.parameters = {
  27180. shapes: shapes,
  27181. curveSegments: curveSegments
  27182. };
  27183. // buffers
  27184. const indices = [];
  27185. const vertices = [];
  27186. const normals = [];
  27187. const uvs = [];
  27188. // helper variables
  27189. let groupStart = 0;
  27190. let groupCount = 0;
  27191. // allow single and array values for "shapes" parameter
  27192. if ( Array.isArray( shapes ) === false ) {
  27193. addShape( shapes );
  27194. } else {
  27195. for ( let i = 0; i < shapes.length; i ++ ) {
  27196. addShape( shapes[ i ] );
  27197. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  27198. groupStart += groupCount;
  27199. groupCount = 0;
  27200. }
  27201. }
  27202. // build geometry
  27203. this.setIndex( indices );
  27204. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27205. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27206. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27207. // helper functions
  27208. function addShape( shape ) {
  27209. const indexOffset = vertices.length / 3;
  27210. const points = shape.extractPoints( curveSegments );
  27211. let shapeVertices = points.shape;
  27212. const shapeHoles = points.holes;
  27213. // check direction of vertices
  27214. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  27215. shapeVertices = shapeVertices.reverse();
  27216. }
  27217. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27218. const shapeHole = shapeHoles[ i ];
  27219. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  27220. shapeHoles[ i ] = shapeHole.reverse();
  27221. }
  27222. }
  27223. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  27224. // join vertices of inner and outer paths to a single array
  27225. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27226. const shapeHole = shapeHoles[ i ];
  27227. shapeVertices = shapeVertices.concat( shapeHole );
  27228. }
  27229. // vertices, normals, uvs
  27230. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  27231. const vertex = shapeVertices[ i ];
  27232. vertices.push( vertex.x, vertex.y, 0 );
  27233. normals.push( 0, 0, 1 );
  27234. uvs.push( vertex.x, vertex.y ); // world uvs
  27235. }
  27236. // indices
  27237. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  27238. const face = faces[ i ];
  27239. const a = face[ 0 ] + indexOffset;
  27240. const b = face[ 1 ] + indexOffset;
  27241. const c = face[ 2 ] + indexOffset;
  27242. indices.push( a, b, c );
  27243. groupCount += 3;
  27244. }
  27245. }
  27246. }
  27247. copy( source ) {
  27248. super.copy( source );
  27249. this.parameters = Object.assign( {}, source.parameters );
  27250. return this;
  27251. }
  27252. toJSON() {
  27253. const data = super.toJSON();
  27254. const shapes = this.parameters.shapes;
  27255. return toJSON( shapes, data );
  27256. }
  27257. /**
  27258. * Factory method for creating an instance of this class from the given
  27259. * JSON object.
  27260. *
  27261. * @param {Object} data - A JSON object representing the serialized geometry.
  27262. * @param {Array<Shape>} shapes - An array of shapes.
  27263. * @return {ShapeGeometry} A new instance.
  27264. */
  27265. static fromJSON( data, shapes ) {
  27266. const geometryShapes = [];
  27267. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27268. const shape = shapes[ data.shapes[ j ] ];
  27269. geometryShapes.push( shape );
  27270. }
  27271. return new ShapeGeometry( geometryShapes, data.curveSegments );
  27272. }
  27273. }
  27274. function toJSON( shapes, data ) {
  27275. data.shapes = [];
  27276. if ( Array.isArray( shapes ) ) {
  27277. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  27278. const shape = shapes[ i ];
  27279. data.shapes.push( shape.uuid );
  27280. }
  27281. } else {
  27282. data.shapes.push( shapes.uuid );
  27283. }
  27284. return data;
  27285. }
  27286. /**
  27287. * A class for generating a sphere geometry.
  27288. *
  27289. * ```js
  27290. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  27291. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27292. * const sphere = new THREE.Mesh( geometry, material );
  27293. * scene.add( sphere );
  27294. * ```
  27295. *
  27296. * @augments BufferGeometry
  27297. * @demo scenes/geometry-browser.html#SphereGeometry
  27298. */
  27299. class SphereGeometry extends BufferGeometry {
  27300. /**
  27301. * Constructs a new sphere geometry.
  27302. *
  27303. * @param {number} [radius=1] - The sphere radius.
  27304. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  27305. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  27306. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  27307. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  27308. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  27309. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  27310. */
  27311. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  27312. super();
  27313. this.type = 'SphereGeometry';
  27314. /**
  27315. * Holds the constructor parameters that have been
  27316. * used to generate the geometry. Any modification
  27317. * after instantiation does not change the geometry.
  27318. *
  27319. * @type {Object}
  27320. */
  27321. this.parameters = {
  27322. radius: radius,
  27323. widthSegments: widthSegments,
  27324. heightSegments: heightSegments,
  27325. phiStart: phiStart,
  27326. phiLength: phiLength,
  27327. thetaStart: thetaStart,
  27328. thetaLength: thetaLength
  27329. };
  27330. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  27331. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  27332. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  27333. let index = 0;
  27334. const grid = [];
  27335. const vertex = new Vector3();
  27336. const normal = new Vector3();
  27337. // buffers
  27338. const indices = [];
  27339. const vertices = [];
  27340. const normals = [];
  27341. const uvs = [];
  27342. // generate vertices, normals and uvs
  27343. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  27344. const verticesRow = [];
  27345. const v = iy / heightSegments;
  27346. // special case for the poles
  27347. let uOffset = 0;
  27348. if ( iy === 0 && thetaStart === 0 ) {
  27349. uOffset = 0.5 / widthSegments;
  27350. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  27351. uOffset = -0.5 / widthSegments;
  27352. }
  27353. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  27354. const u = ix / widthSegments;
  27355. // vertex
  27356. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27357. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  27358. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27359. vertices.push( vertex.x, vertex.y, vertex.z );
  27360. // normal
  27361. normal.copy( vertex ).normalize();
  27362. normals.push( normal.x, normal.y, normal.z );
  27363. // uv
  27364. uvs.push( u + uOffset, 1 - v );
  27365. verticesRow.push( index ++ );
  27366. }
  27367. grid.push( verticesRow );
  27368. }
  27369. // indices
  27370. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  27371. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  27372. const a = grid[ iy ][ ix + 1 ];
  27373. const b = grid[ iy ][ ix ];
  27374. const c = grid[ iy + 1 ][ ix ];
  27375. const d = grid[ iy + 1 ][ ix + 1 ];
  27376. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  27377. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  27378. }
  27379. }
  27380. // build geometry
  27381. this.setIndex( indices );
  27382. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27383. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27384. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27385. }
  27386. copy( source ) {
  27387. super.copy( source );
  27388. this.parameters = Object.assign( {}, source.parameters );
  27389. return this;
  27390. }
  27391. /**
  27392. * Factory method for creating an instance of this class from the given
  27393. * JSON object.
  27394. *
  27395. * @param {Object} data - A JSON object representing the serialized geometry.
  27396. * @return {SphereGeometry} A new instance.
  27397. */
  27398. static fromJSON( data ) {
  27399. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  27400. }
  27401. }
  27402. /**
  27403. * A geometry class for representing an tetrahedron.
  27404. *
  27405. * ```js
  27406. * const geometry = new THREE.TetrahedronGeometry();
  27407. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27408. * const tetrahedron = new THREE.Mesh( geometry, material );
  27409. * scene.add( tetrahedron );
  27410. * ```
  27411. *
  27412. * @augments PolyhedronGeometry
  27413. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  27414. */
  27415. class TetrahedronGeometry extends PolyhedronGeometry {
  27416. /**
  27417. * Constructs a new tetrahedron geometry.
  27418. *
  27419. * @param {number} [radius=1] - Radius of the tetrahedron.
  27420. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  27421. */
  27422. constructor( radius = 1, detail = 0 ) {
  27423. const vertices = [
  27424. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  27425. ];
  27426. const indices = [
  27427. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  27428. ];
  27429. super( vertices, indices, radius, detail );
  27430. this.type = 'TetrahedronGeometry';
  27431. /**
  27432. * Holds the constructor parameters that have been
  27433. * used to generate the geometry. Any modification
  27434. * after instantiation does not change the geometry.
  27435. *
  27436. * @type {Object}
  27437. */
  27438. this.parameters = {
  27439. radius: radius,
  27440. detail: detail
  27441. };
  27442. }
  27443. /**
  27444. * Factory method for creating an instance of this class from the given
  27445. * JSON object.
  27446. *
  27447. * @param {Object} data - A JSON object representing the serialized geometry.
  27448. * @return {TetrahedronGeometry} A new instance.
  27449. */
  27450. static fromJSON( data ) {
  27451. return new TetrahedronGeometry( data.radius, data.detail );
  27452. }
  27453. }
  27454. /**
  27455. * A geometry class for representing an torus.
  27456. *
  27457. * ```js
  27458. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  27459. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27460. * const torus = new THREE.Mesh( geometry, material );
  27461. * scene.add( torus );
  27462. * ```
  27463. *
  27464. * @augments BufferGeometry
  27465. * @demo scenes/geometry-browser.html#TorusGeometry
  27466. */
  27467. class TorusGeometry extends BufferGeometry {
  27468. /**
  27469. * Constructs a new torus geometry.
  27470. *
  27471. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  27472. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  27473. * @param {number} [radialSegments=12] - The number of radial segments.
  27474. * @param {number} [tubularSegments=48] - The number of tubular segments.
  27475. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  27476. * @param {number} [thetaStart=0] - Start of the tubular sweep in radians.
  27477. * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians.
  27478. */
  27479. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  27480. super();
  27481. this.type = 'TorusGeometry';
  27482. /**
  27483. * Holds the constructor parameters that have been
  27484. * used to generate the geometry. Any modification
  27485. * after instantiation does not change the geometry.
  27486. *
  27487. * @type {Object}
  27488. */
  27489. this.parameters = {
  27490. radius: radius,
  27491. tube: tube,
  27492. radialSegments: radialSegments,
  27493. tubularSegments: tubularSegments,
  27494. arc: arc,
  27495. thetaStart: thetaStart,
  27496. thetaLength: thetaLength,
  27497. };
  27498. radialSegments = Math.floor( radialSegments );
  27499. tubularSegments = Math.floor( tubularSegments );
  27500. // buffers
  27501. const indices = [];
  27502. const vertices = [];
  27503. const normals = [];
  27504. const uvs = [];
  27505. // helper variables
  27506. const center = new Vector3();
  27507. const vertex = new Vector3();
  27508. const normal = new Vector3();
  27509. // generate vertices, normals and uvs
  27510. for ( let j = 0; j <= radialSegments; j ++ ) {
  27511. const v = thetaStart + ( j / radialSegments ) * thetaLength;
  27512. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27513. const u = i / tubularSegments * arc;
  27514. // vertex
  27515. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27516. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27517. vertex.z = tube * Math.sin( v );
  27518. vertices.push( vertex.x, vertex.y, vertex.z );
  27519. // normal
  27520. center.x = radius * Math.cos( u );
  27521. center.y = radius * Math.sin( u );
  27522. normal.subVectors( vertex, center ).normalize();
  27523. normals.push( normal.x, normal.y, normal.z );
  27524. // uv
  27525. uvs.push( i / tubularSegments );
  27526. uvs.push( j / radialSegments );
  27527. }
  27528. }
  27529. // generate indices
  27530. for ( let j = 1; j <= radialSegments; j ++ ) {
  27531. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27532. // indices
  27533. const a = ( tubularSegments + 1 ) * j + i - 1;
  27534. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27535. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27536. const d = ( tubularSegments + 1 ) * j + i;
  27537. // faces
  27538. indices.push( a, b, d );
  27539. indices.push( b, c, d );
  27540. }
  27541. }
  27542. // build geometry
  27543. this.setIndex( indices );
  27544. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27545. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27546. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27547. }
  27548. copy( source ) {
  27549. super.copy( source );
  27550. this.parameters = Object.assign( {}, source.parameters );
  27551. return this;
  27552. }
  27553. /**
  27554. * Factory method for creating an instance of this class from the given
  27555. * JSON object.
  27556. *
  27557. * @param {Object} data - A JSON object representing the serialized geometry.
  27558. * @return {TorusGeometry} A new instance.
  27559. */
  27560. static fromJSON( data ) {
  27561. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27562. }
  27563. }
  27564. /**
  27565. * Creates a torus knot, the particular shape of which is defined by a pair
  27566. * of coprime integers, p and q. If p and q are not coprime, the result will
  27567. * be a torus link.
  27568. *
  27569. * ```js
  27570. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27571. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27572. * const torusKnot = new THREE.Mesh( geometry, material );
  27573. * scene.add( torusKnot );
  27574. * ```
  27575. *
  27576. * @augments BufferGeometry
  27577. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  27578. */
  27579. class TorusKnotGeometry extends BufferGeometry {
  27580. /**
  27581. * Constructs a new torus knot geometry.
  27582. *
  27583. * @param {number} [radius=1] - Radius of the torus knot.
  27584. * @param {number} [tube=0.4] - Radius of the tube.
  27585. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27586. * @param {number} [radialSegments=8] - The number of radial segments.
  27587. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27588. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27589. */
  27590. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27591. super();
  27592. this.type = 'TorusKnotGeometry';
  27593. /**
  27594. * Holds the constructor parameters that have been
  27595. * used to generate the geometry. Any modification
  27596. * after instantiation does not change the geometry.
  27597. *
  27598. * @type {Object}
  27599. */
  27600. this.parameters = {
  27601. radius: radius,
  27602. tube: tube,
  27603. tubularSegments: tubularSegments,
  27604. radialSegments: radialSegments,
  27605. p: p,
  27606. q: q
  27607. };
  27608. tubularSegments = Math.floor( tubularSegments );
  27609. radialSegments = Math.floor( radialSegments );
  27610. // buffers
  27611. const indices = [];
  27612. const vertices = [];
  27613. const normals = [];
  27614. const uvs = [];
  27615. // helper variables
  27616. const vertex = new Vector3();
  27617. const normal = new Vector3();
  27618. const P1 = new Vector3();
  27619. const P2 = new Vector3();
  27620. const B = new Vector3();
  27621. const T = new Vector3();
  27622. const N = new Vector3();
  27623. // generate vertices, normals and uvs
  27624. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27625. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27626. const u = i / tubularSegments * p * Math.PI * 2;
  27627. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27628. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27629. calculatePositionOnCurve( u, p, q, radius, P1 );
  27630. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27631. // calculate orthonormal basis
  27632. T.subVectors( P2, P1 );
  27633. N.addVectors( P2, P1 );
  27634. B.crossVectors( T, N );
  27635. N.crossVectors( B, T );
  27636. // normalize B, N. T can be ignored, we don't use it
  27637. B.normalize();
  27638. N.normalize();
  27639. for ( let j = 0; j <= radialSegments; ++ j ) {
  27640. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27641. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27642. const v = j / radialSegments * Math.PI * 2;
  27643. const cx = - tube * Math.cos( v );
  27644. const cy = tube * Math.sin( v );
  27645. // now calculate the final vertex position.
  27646. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27647. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27648. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27649. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27650. vertices.push( vertex.x, vertex.y, vertex.z );
  27651. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27652. normal.subVectors( vertex, P1 ).normalize();
  27653. normals.push( normal.x, normal.y, normal.z );
  27654. // uv
  27655. uvs.push( i / tubularSegments );
  27656. uvs.push( j / radialSegments );
  27657. }
  27658. }
  27659. // generate indices
  27660. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27661. for ( let i = 1; i <= radialSegments; i ++ ) {
  27662. // indices
  27663. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27664. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27665. const c = ( radialSegments + 1 ) * j + i;
  27666. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27667. // faces
  27668. indices.push( a, b, d );
  27669. indices.push( b, c, d );
  27670. }
  27671. }
  27672. // build geometry
  27673. this.setIndex( indices );
  27674. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27675. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27676. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27677. // this function calculates the current position on the torus curve
  27678. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27679. const cu = Math.cos( u );
  27680. const su = Math.sin( u );
  27681. const quOverP = q / p * u;
  27682. const cs = Math.cos( quOverP );
  27683. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27684. position.y = radius * ( 2 + cs ) * su * 0.5;
  27685. position.z = radius * Math.sin( quOverP ) * 0.5;
  27686. }
  27687. }
  27688. copy( source ) {
  27689. super.copy( source );
  27690. this.parameters = Object.assign( {}, source.parameters );
  27691. return this;
  27692. }
  27693. /**
  27694. * Factory method for creating an instance of this class from the given
  27695. * JSON object.
  27696. *
  27697. * @param {Object} data - A JSON object representing the serialized geometry.
  27698. * @return {TorusKnotGeometry} A new instance.
  27699. */
  27700. static fromJSON( data ) {
  27701. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27702. }
  27703. }
  27704. /**
  27705. * Creates a tube that extrudes along a 3D curve.
  27706. *
  27707. * ```js
  27708. * class CustomSinCurve extends THREE.Curve {
  27709. *
  27710. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27711. *
  27712. * const tx = t * 3 - 1.5;
  27713. * const ty = Math.sin( 2 * Math.PI * t );
  27714. * const tz = 0;
  27715. *
  27716. * return optionalTarget.set( tx, ty, tz );
  27717. * }
  27718. *
  27719. * }
  27720. *
  27721. * const path = new CustomSinCurve( 10 );
  27722. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27723. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27724. * const mesh = new THREE.Mesh( geometry, material );
  27725. * scene.add( mesh );
  27726. * ```
  27727. *
  27728. * @augments BufferGeometry
  27729. * @demo scenes/geometry-browser.html#TubeGeometry
  27730. */
  27731. class TubeGeometry extends BufferGeometry {
  27732. /**
  27733. * Constructs a new tube geometry.
  27734. *
  27735. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27736. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27737. * @param {number} [radius=1] -The radius of the tube.
  27738. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27739. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27740. */
  27741. 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 ) {
  27742. super();
  27743. this.type = 'TubeGeometry';
  27744. /**
  27745. * Holds the constructor parameters that have been
  27746. * used to generate the geometry. Any modification
  27747. * after instantiation does not change the geometry.
  27748. *
  27749. * @type {Object}
  27750. */
  27751. this.parameters = {
  27752. path: path,
  27753. tubularSegments: tubularSegments,
  27754. radius: radius,
  27755. radialSegments: radialSegments,
  27756. closed: closed
  27757. };
  27758. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27759. // expose internals
  27760. this.tangents = frames.tangents;
  27761. this.normals = frames.normals;
  27762. this.binormals = frames.binormals;
  27763. // helper variables
  27764. const vertex = new Vector3();
  27765. const normal = new Vector3();
  27766. const uv = new Vector2();
  27767. let P = new Vector3();
  27768. // buffer
  27769. const vertices = [];
  27770. const normals = [];
  27771. const uvs = [];
  27772. const indices = [];
  27773. // create buffer data
  27774. generateBufferData();
  27775. // build geometry
  27776. this.setIndex( indices );
  27777. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27778. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27779. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27780. // functions
  27781. function generateBufferData() {
  27782. for ( let i = 0; i < tubularSegments; i ++ ) {
  27783. generateSegment( i );
  27784. }
  27785. // if the geometry is not closed, generate the last row of vertices and normals
  27786. // at the regular position on the given path
  27787. //
  27788. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27789. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27790. // uvs are generated in a separate function.
  27791. // this makes it easy compute correct values for closed geometries
  27792. generateUVs();
  27793. // finally create faces
  27794. generateIndices();
  27795. }
  27796. function generateSegment( i ) {
  27797. // we use getPointAt to sample evenly distributed points from the given path
  27798. P = path.getPointAt( i / tubularSegments, P );
  27799. // retrieve corresponding normal and binormal
  27800. const N = frames.normals[ i ];
  27801. const B = frames.binormals[ i ];
  27802. // generate normals and vertices for the current segment
  27803. for ( let j = 0; j <= radialSegments; j ++ ) {
  27804. const v = j / radialSegments * Math.PI * 2;
  27805. const sin = Math.sin( v );
  27806. const cos = - Math.cos( v );
  27807. // normal
  27808. normal.x = ( cos * N.x + sin * B.x );
  27809. normal.y = ( cos * N.y + sin * B.y );
  27810. normal.z = ( cos * N.z + sin * B.z );
  27811. normal.normalize();
  27812. normals.push( normal.x, normal.y, normal.z );
  27813. // vertex
  27814. vertex.x = P.x + radius * normal.x;
  27815. vertex.y = P.y + radius * normal.y;
  27816. vertex.z = P.z + radius * normal.z;
  27817. vertices.push( vertex.x, vertex.y, vertex.z );
  27818. }
  27819. }
  27820. function generateIndices() {
  27821. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27822. for ( let i = 1; i <= radialSegments; i ++ ) {
  27823. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27824. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27825. const c = ( radialSegments + 1 ) * j + i;
  27826. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27827. // faces
  27828. indices.push( a, b, d );
  27829. indices.push( b, c, d );
  27830. }
  27831. }
  27832. }
  27833. function generateUVs() {
  27834. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27835. for ( let j = 0; j <= radialSegments; j ++ ) {
  27836. uv.x = i / tubularSegments;
  27837. uv.y = j / radialSegments;
  27838. uvs.push( uv.x, uv.y );
  27839. }
  27840. }
  27841. }
  27842. }
  27843. copy( source ) {
  27844. super.copy( source );
  27845. this.parameters = Object.assign( {}, source.parameters );
  27846. return this;
  27847. }
  27848. toJSON() {
  27849. const data = super.toJSON();
  27850. data.path = this.parameters.path.toJSON();
  27851. return data;
  27852. }
  27853. /**
  27854. * Factory method for creating an instance of this class from the given
  27855. * JSON object.
  27856. *
  27857. * @param {Object} data - A JSON object representing the serialized geometry.
  27858. * @return {TubeGeometry} A new instance.
  27859. */
  27860. static fromJSON( data ) {
  27861. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27862. // User defined curves or instances of CurvePath will not be deserialized.
  27863. return new TubeGeometry(
  27864. new Curves[ data.path.type ]().fromJSON( data.path ),
  27865. data.tubularSegments,
  27866. data.radius,
  27867. data.radialSegments,
  27868. data.closed
  27869. );
  27870. }
  27871. }
  27872. /**
  27873. * Can be used as a helper object to visualize a geometry as a wireframe.
  27874. *
  27875. * ```js
  27876. * const geometry = new THREE.SphereGeometry();
  27877. *
  27878. * const wireframe = new THREE.WireframeGeometry( geometry );
  27879. *
  27880. * const line = new THREE.LineSegments( wireframe );
  27881. * line.material.depthWrite = false;
  27882. * line.material.opacity = 0.25;
  27883. * line.material.transparent = true;
  27884. *
  27885. * scene.add( line );
  27886. * ```
  27887. *
  27888. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27889. *
  27890. * @augments BufferGeometry
  27891. */
  27892. class WireframeGeometry extends BufferGeometry {
  27893. /**
  27894. * Constructs a new wireframe geometry.
  27895. *
  27896. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27897. */
  27898. constructor( geometry = null ) {
  27899. super();
  27900. this.type = 'WireframeGeometry';
  27901. /**
  27902. * Holds the constructor parameters that have been
  27903. * used to generate the geometry. Any modification
  27904. * after instantiation does not change the geometry.
  27905. *
  27906. * @type {Object}
  27907. */
  27908. this.parameters = {
  27909. geometry: geometry
  27910. };
  27911. if ( geometry !== null ) {
  27912. // buffer
  27913. const vertices = [];
  27914. const edges = new Set();
  27915. // helper variables
  27916. const start = new Vector3();
  27917. const end = new Vector3();
  27918. if ( geometry.index !== null ) {
  27919. // indexed BufferGeometry
  27920. const position = geometry.attributes.position;
  27921. const indices = geometry.index;
  27922. let groups = geometry.groups;
  27923. if ( groups.length === 0 ) {
  27924. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27925. }
  27926. // create a data structure that contains all edges without duplicates
  27927. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27928. const group = groups[ o ];
  27929. const groupStart = group.start;
  27930. const groupCount = group.count;
  27931. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27932. for ( let j = 0; j < 3; j ++ ) {
  27933. const index1 = indices.getX( i + j );
  27934. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27935. start.fromBufferAttribute( position, index1 );
  27936. end.fromBufferAttribute( position, index2 );
  27937. if ( isUniqueEdge( start, end, edges ) === true ) {
  27938. vertices.push( start.x, start.y, start.z );
  27939. vertices.push( end.x, end.y, end.z );
  27940. }
  27941. }
  27942. }
  27943. }
  27944. } else {
  27945. // non-indexed BufferGeometry
  27946. const position = geometry.attributes.position;
  27947. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27948. for ( let j = 0; j < 3; j ++ ) {
  27949. // three edges per triangle, an edge is represented as (index1, index2)
  27950. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27951. const index1 = 3 * i + j;
  27952. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27953. start.fromBufferAttribute( position, index1 );
  27954. end.fromBufferAttribute( position, index2 );
  27955. if ( isUniqueEdge( start, end, edges ) === true ) {
  27956. vertices.push( start.x, start.y, start.z );
  27957. vertices.push( end.x, end.y, end.z );
  27958. }
  27959. }
  27960. }
  27961. }
  27962. // build geometry
  27963. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27964. }
  27965. }
  27966. copy( source ) {
  27967. super.copy( source );
  27968. this.parameters = Object.assign( {}, source.parameters );
  27969. return this;
  27970. }
  27971. }
  27972. function isUniqueEdge( start, end, edges ) {
  27973. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27974. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27975. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27976. return false;
  27977. } else {
  27978. edges.add( hash1 );
  27979. edges.add( hash2 );
  27980. return true;
  27981. }
  27982. }
  27983. var Geometries = /*#__PURE__*/Object.freeze({
  27984. __proto__: null,
  27985. BoxGeometry: BoxGeometry,
  27986. CapsuleGeometry: CapsuleGeometry,
  27987. CircleGeometry: CircleGeometry,
  27988. ConeGeometry: ConeGeometry,
  27989. CylinderGeometry: CylinderGeometry,
  27990. DodecahedronGeometry: DodecahedronGeometry,
  27991. EdgesGeometry: EdgesGeometry,
  27992. ExtrudeGeometry: ExtrudeGeometry,
  27993. IcosahedronGeometry: IcosahedronGeometry,
  27994. LatheGeometry: LatheGeometry,
  27995. OctahedronGeometry: OctahedronGeometry,
  27996. PlaneGeometry: PlaneGeometry,
  27997. PolyhedronGeometry: PolyhedronGeometry,
  27998. RingGeometry: RingGeometry,
  27999. ShapeGeometry: ShapeGeometry,
  28000. SphereGeometry: SphereGeometry,
  28001. TetrahedronGeometry: TetrahedronGeometry,
  28002. TorusGeometry: TorusGeometry,
  28003. TorusKnotGeometry: TorusKnotGeometry,
  28004. TubeGeometry: TubeGeometry,
  28005. WireframeGeometry: WireframeGeometry
  28006. });
  28007. /**
  28008. * This material can receive shadows, but otherwise is completely transparent.
  28009. *
  28010. * ```js
  28011. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  28012. * geometry.rotateX( - Math.PI / 2 );
  28013. *
  28014. * const material = new THREE.ShadowMaterial();
  28015. * material.opacity = 0.2;
  28016. *
  28017. * const plane = new THREE.Mesh( geometry, material );
  28018. * plane.position.y = -200;
  28019. * plane.receiveShadow = true;
  28020. * scene.add( plane );
  28021. * ```
  28022. *
  28023. * @augments Material
  28024. */
  28025. class ShadowMaterial extends Material {
  28026. /**
  28027. * Constructs a new shadow material.
  28028. *
  28029. * @param {Object} [parameters] - An object with one or more properties
  28030. * defining the material's appearance. Any property of the material
  28031. * (including any property from inherited materials) can be passed
  28032. * in here. Color values can be passed any type of value accepted
  28033. * by {@link Color#set}.
  28034. */
  28035. constructor( parameters ) {
  28036. super();
  28037. /**
  28038. * This flag can be used for type testing.
  28039. *
  28040. * @type {boolean}
  28041. * @readonly
  28042. * @default true
  28043. */
  28044. this.isShadowMaterial = true;
  28045. this.type = 'ShadowMaterial';
  28046. /**
  28047. * Color of the material.
  28048. *
  28049. * @type {Color}
  28050. * @default (0,0,0)
  28051. */
  28052. this.color = new Color( 0x000000 );
  28053. /**
  28054. * Overwritten since shadow materials are transparent
  28055. * by default.
  28056. *
  28057. * @type {boolean}
  28058. * @default true
  28059. */
  28060. this.transparent = true;
  28061. /**
  28062. * Whether the material is affected by fog or not.
  28063. *
  28064. * @type {boolean}
  28065. * @default true
  28066. */
  28067. this.fog = true;
  28068. this.setValues( parameters );
  28069. }
  28070. copy( source ) {
  28071. super.copy( source );
  28072. this.color.copy( source.color );
  28073. this.fog = source.fog;
  28074. return this;
  28075. }
  28076. }
  28077. /**
  28078. * This class works just like {@link ShaderMaterial}, except that definitions
  28079. * of built-in uniforms and attributes are not automatically prepended to the
  28080. * GLSL shader code.
  28081. *
  28082. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  28083. *
  28084. * @augments ShaderMaterial
  28085. */
  28086. class RawShaderMaterial extends ShaderMaterial {
  28087. /**
  28088. * Constructs a new raw shader material.
  28089. *
  28090. * @param {Object} [parameters] - An object with one or more properties
  28091. * defining the material's appearance. Any property of the material
  28092. * (including any property from inherited materials) can be passed
  28093. * in here. Color values can be passed any type of value accepted
  28094. * by {@link Color#set}.
  28095. */
  28096. constructor( parameters ) {
  28097. super( parameters );
  28098. /**
  28099. * This flag can be used for type testing.
  28100. *
  28101. * @type {boolean}
  28102. * @readonly
  28103. * @default true
  28104. */
  28105. this.isRawShaderMaterial = true;
  28106. this.type = 'RawShaderMaterial';
  28107. }
  28108. }
  28109. /**
  28110. * A standard physically based material, using Metallic-Roughness workflow.
  28111. *
  28112. * Physically based rendering (PBR) has recently become the standard in many
  28113. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  28114. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  28115. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  28116. *
  28117. * This approach differs from older approaches in that instead of using
  28118. * approximations for the way in which light interacts with a surface, a
  28119. * physically correct model is used. The idea is that, instead of tweaking
  28120. * materials to look good under specific lighting, a material can be created
  28121. * that will react 'correctly' under all lighting scenarios.
  28122. *
  28123. * In practice this gives a more accurate and realistic looking result than
  28124. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  28125. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  28126. * shading.
  28127. *
  28128. * Note that for best results you should always specify an environment map when using this material.
  28129. *
  28130. * For a non-technical introduction to the concept of PBR and how to set up a
  28131. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  28132. *
  28133. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  28134. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  28135. *
  28136. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  28137. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  28138. * (pdf), by Brent Burley.
  28139. *
  28140. * @augments Material
  28141. * @demo scenes/material-browser.html#MeshStandardMaterial
  28142. */
  28143. class MeshStandardMaterial extends Material {
  28144. /**
  28145. * Constructs a new mesh standard material.
  28146. *
  28147. * @param {Object} [parameters] - An object with one or more properties
  28148. * defining the material's appearance. Any property of the material
  28149. * (including any property from inherited materials) can be passed
  28150. * in here. Color values can be passed any type of value accepted
  28151. * by {@link Color#set}.
  28152. */
  28153. constructor( parameters ) {
  28154. super();
  28155. /**
  28156. * This flag can be used for type testing.
  28157. *
  28158. * @type {boolean}
  28159. * @readonly
  28160. * @default true
  28161. */
  28162. this.isMeshStandardMaterial = true;
  28163. this.type = 'MeshStandardMaterial';
  28164. this.defines = { 'STANDARD': '' };
  28165. /**
  28166. * Color of the material.
  28167. *
  28168. * @type {Color}
  28169. * @default (1,1,1)
  28170. */
  28171. this.color = new Color( 0xffffff ); // diffuse
  28172. /**
  28173. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  28174. * means fully diffuse. If `roughnessMap` is also provided,
  28175. * both values are multiplied.
  28176. *
  28177. * @type {number}
  28178. * @default 1
  28179. */
  28180. this.roughness = 1.0;
  28181. /**
  28182. * How much the material is like a metal. Non-metallic materials such as wood
  28183. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  28184. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  28185. * If `metalnessMap` is also provided, both values are multiplied.
  28186. *
  28187. * @type {number}
  28188. * @default 0
  28189. */
  28190. this.metalness = 0.0;
  28191. /**
  28192. * The color map. May optionally include an alpha channel, typically combined
  28193. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28194. * color is modulated by the diffuse `color`.
  28195. *
  28196. * @type {?Texture}
  28197. * @default null
  28198. */
  28199. this.map = null;
  28200. /**
  28201. * The light map. Requires a second set of UVs.
  28202. *
  28203. * @type {?Texture}
  28204. * @default null
  28205. */
  28206. this.lightMap = null;
  28207. /**
  28208. * Intensity of the baked light.
  28209. *
  28210. * @type {number}
  28211. * @default 1
  28212. */
  28213. this.lightMapIntensity = 1.0;
  28214. /**
  28215. * The red channel of this texture is used as the ambient occlusion map.
  28216. * Requires a second set of UVs.
  28217. *
  28218. * @type {?Texture}
  28219. * @default null
  28220. */
  28221. this.aoMap = null;
  28222. /**
  28223. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28224. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28225. * red channel is also `1`, ambient light is fully occluded on a surface.
  28226. *
  28227. * @type {number}
  28228. * @default 1
  28229. */
  28230. this.aoMapIntensity = 1.0;
  28231. /**
  28232. * Emissive (light) color of the material, essentially a solid color
  28233. * unaffected by other lighting.
  28234. *
  28235. * @type {Color}
  28236. * @default (0,0,0)
  28237. */
  28238. this.emissive = new Color( 0x000000 );
  28239. /**
  28240. * Intensity of the emissive light. Modulates the emissive color.
  28241. *
  28242. * @type {number}
  28243. * @default 1
  28244. */
  28245. this.emissiveIntensity = 1.0;
  28246. /**
  28247. * Set emissive (glow) map. The emissive map color is modulated by the
  28248. * emissive color and the emissive intensity. If you have an emissive map,
  28249. * be sure to set the emissive color to something other than black.
  28250. *
  28251. * @type {?Texture}
  28252. * @default null
  28253. */
  28254. this.emissiveMap = null;
  28255. /**
  28256. * The texture to create a bump map. The black and white values map to the
  28257. * perceived depth in relation to the lights. Bump doesn't actually affect
  28258. * the geometry of the object, only the lighting. If a normal map is defined
  28259. * this will be ignored.
  28260. *
  28261. * @type {?Texture}
  28262. * @default null
  28263. */
  28264. this.bumpMap = null;
  28265. /**
  28266. * How much the bump map affects the material. Typical range is `[0,1]`.
  28267. *
  28268. * @type {number}
  28269. * @default 1
  28270. */
  28271. this.bumpScale = 1;
  28272. /**
  28273. * The texture to create a normal map. The RGB values affect the surface
  28274. * normal for each pixel fragment and change the way the color is lit. Normal
  28275. * maps do not change the actual shape of the surface, only the lighting. In
  28276. * case the material has a normal map authored using the left handed
  28277. * convention, the `y` component of `normalScale` should be negated to compensate
  28278. * for the different handedness.
  28279. *
  28280. * @type {?Texture}
  28281. * @default null
  28282. */
  28283. this.normalMap = null;
  28284. /**
  28285. * The type of normal map.
  28286. *
  28287. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28288. * @default TangentSpaceNormalMap
  28289. */
  28290. this.normalMapType = TangentSpaceNormalMap;
  28291. /**
  28292. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28293. *
  28294. * @type {Vector2}
  28295. * @default (1,1)
  28296. */
  28297. this.normalScale = new Vector2( 1, 1 );
  28298. /**
  28299. * The displacement map affects the position of the mesh's vertices. Unlike
  28300. * other maps which only affect the light and shade of the material the
  28301. * displaced vertices can cast shadows, block other objects, and otherwise
  28302. * act as real geometry. The displacement texture is an image where the value
  28303. * of each pixel (white being the highest) is mapped against, and
  28304. * repositions, the vertices of the mesh.
  28305. *
  28306. * @type {?Texture}
  28307. * @default null
  28308. */
  28309. this.displacementMap = null;
  28310. /**
  28311. * How much the displacement map affects the mesh (where black is no
  28312. * displacement, and white is maximum displacement). Without a displacement
  28313. * map set, this value is not applied.
  28314. *
  28315. * @type {number}
  28316. * @default 0
  28317. */
  28318. this.displacementScale = 1;
  28319. /**
  28320. * The offset of the displacement map's values on the mesh's vertices.
  28321. * The bias is added to the scaled sample of the displacement map.
  28322. * Without a displacement map set, this value is not applied.
  28323. *
  28324. * @type {number}
  28325. * @default 0
  28326. */
  28327. this.displacementBias = 0;
  28328. /**
  28329. * The green channel of this texture is used to alter the roughness of the
  28330. * material.
  28331. *
  28332. * @type {?Texture}
  28333. * @default null
  28334. */
  28335. this.roughnessMap = null;
  28336. /**
  28337. * The blue channel of this texture is used to alter the metalness of the
  28338. * material.
  28339. *
  28340. * @type {?Texture}
  28341. * @default null
  28342. */
  28343. this.metalnessMap = null;
  28344. /**
  28345. * The alpha map is a grayscale texture that controls the opacity across the
  28346. * surface (black: fully transparent; white: fully opaque).
  28347. *
  28348. * Only the color of the texture is used, ignoring the alpha channel if one
  28349. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28350. * when sampling this texture due to the extra bit of precision provided for
  28351. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28352. * luminance/alpha textures will also still work as expected.
  28353. *
  28354. * @type {?Texture}
  28355. * @default null
  28356. */
  28357. this.alphaMap = null;
  28358. /**
  28359. * The environment map. To ensure a physically correct rendering, environment maps
  28360. * are internally pre-processed with {@link PMREMGenerator}.
  28361. *
  28362. * @type {?Texture}
  28363. * @default null
  28364. */
  28365. this.envMap = null;
  28366. /**
  28367. * The rotation of the environment map in radians.
  28368. *
  28369. * @type {Euler}
  28370. * @default (0,0,0)
  28371. */
  28372. this.envMapRotation = new Euler();
  28373. /**
  28374. * Scales the effect of the environment map by multiplying its color.
  28375. *
  28376. * @type {number}
  28377. * @default 1
  28378. */
  28379. this.envMapIntensity = 1.0;
  28380. /**
  28381. * Renders the geometry as a wireframe.
  28382. *
  28383. * @type {boolean}
  28384. * @default false
  28385. */
  28386. this.wireframe = false;
  28387. /**
  28388. * Controls the thickness of the wireframe.
  28389. *
  28390. * Can only be used with {@link SVGRenderer}.
  28391. *
  28392. * @type {number}
  28393. * @default 1
  28394. */
  28395. this.wireframeLinewidth = 1;
  28396. /**
  28397. * Defines appearance of wireframe ends.
  28398. *
  28399. * Can only be used with {@link SVGRenderer}.
  28400. *
  28401. * @type {('round'|'bevel'|'miter')}
  28402. * @default 'round'
  28403. */
  28404. this.wireframeLinecap = 'round';
  28405. /**
  28406. * Defines appearance of wireframe joints.
  28407. *
  28408. * Can only be used with {@link SVGRenderer}.
  28409. *
  28410. * @type {('round'|'bevel'|'miter')}
  28411. * @default 'round'
  28412. */
  28413. this.wireframeLinejoin = 'round';
  28414. /**
  28415. * Whether the material is rendered with flat shading or not.
  28416. *
  28417. * @type {boolean}
  28418. * @default false
  28419. */
  28420. this.flatShading = false;
  28421. /**
  28422. * Whether the material is affected by fog or not.
  28423. *
  28424. * @type {boolean}
  28425. * @default true
  28426. */
  28427. this.fog = true;
  28428. this.setValues( parameters );
  28429. }
  28430. copy( source ) {
  28431. super.copy( source );
  28432. this.defines = { 'STANDARD': '' };
  28433. this.color.copy( source.color );
  28434. this.roughness = source.roughness;
  28435. this.metalness = source.metalness;
  28436. this.map = source.map;
  28437. this.lightMap = source.lightMap;
  28438. this.lightMapIntensity = source.lightMapIntensity;
  28439. this.aoMap = source.aoMap;
  28440. this.aoMapIntensity = source.aoMapIntensity;
  28441. this.emissive.copy( source.emissive );
  28442. this.emissiveMap = source.emissiveMap;
  28443. this.emissiveIntensity = source.emissiveIntensity;
  28444. this.bumpMap = source.bumpMap;
  28445. this.bumpScale = source.bumpScale;
  28446. this.normalMap = source.normalMap;
  28447. this.normalMapType = source.normalMapType;
  28448. this.normalScale.copy( source.normalScale );
  28449. this.displacementMap = source.displacementMap;
  28450. this.displacementScale = source.displacementScale;
  28451. this.displacementBias = source.displacementBias;
  28452. this.roughnessMap = source.roughnessMap;
  28453. this.metalnessMap = source.metalnessMap;
  28454. this.alphaMap = source.alphaMap;
  28455. this.envMap = source.envMap;
  28456. this.envMapRotation.copy( source.envMapRotation );
  28457. this.envMapIntensity = source.envMapIntensity;
  28458. this.wireframe = source.wireframe;
  28459. this.wireframeLinewidth = source.wireframeLinewidth;
  28460. this.wireframeLinecap = source.wireframeLinecap;
  28461. this.wireframeLinejoin = source.wireframeLinejoin;
  28462. this.flatShading = source.flatShading;
  28463. this.fog = source.fog;
  28464. return this;
  28465. }
  28466. }
  28467. /**
  28468. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28469. * physically-based rendering properties:
  28470. *
  28471. * - Anisotropy: Ability to represent the anisotropic property of materials
  28472. * as observable with brushed metals.
  28473. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28474. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28475. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28476. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28477. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28478. * wings of many insects.
  28479. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28480. * transparent materials are less reflective. Physically-based transmission provides a more
  28481. * realistic option for thin, transparent surfaces like glass.
  28482. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28483. * - Sheen: Can be used for representing cloth and fabric materials.
  28484. *
  28485. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28486. * higher performance cost, per pixel, than other three.js materials. Most
  28487. * effects are disabled by default, and add cost as they are enabled. For
  28488. * best results, always specify an environment map when using this material.
  28489. *
  28490. * @augments MeshStandardMaterial
  28491. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  28492. */
  28493. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28494. /**
  28495. * Constructs a new mesh physical material.
  28496. *
  28497. * @param {Object} [parameters] - An object with one or more properties
  28498. * defining the material's appearance. Any property of the material
  28499. * (including any property from inherited materials) can be passed
  28500. * in here. Color values can be passed any type of value accepted
  28501. * by {@link Color#set}.
  28502. */
  28503. constructor( parameters ) {
  28504. super();
  28505. /**
  28506. * This flag can be used for type testing.
  28507. *
  28508. * @type {boolean}
  28509. * @readonly
  28510. * @default true
  28511. */
  28512. this.isMeshPhysicalMaterial = true;
  28513. this.defines = {
  28514. 'STANDARD': '',
  28515. 'PHYSICAL': ''
  28516. };
  28517. this.type = 'MeshPhysicalMaterial';
  28518. /**
  28519. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28520. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28521. * property provides additional rotation to the vectors in the texture.
  28522. *
  28523. * @type {number}
  28524. * @default 1
  28525. */
  28526. this.anisotropyRotation = 0;
  28527. /**
  28528. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28529. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28530. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28531. *
  28532. * @type {?Texture}
  28533. * @default null
  28534. */
  28535. this.anisotropyMap = null;
  28536. /**
  28537. * The red channel of this texture is multiplied against `clearcoat`,
  28538. * for per-pixel control over a coating's intensity.
  28539. *
  28540. * @type {?Texture}
  28541. * @default null
  28542. */
  28543. this.clearcoatMap = null;
  28544. /**
  28545. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28546. *
  28547. * @type {number}
  28548. * @default 0
  28549. */
  28550. this.clearcoatRoughness = 0.0;
  28551. /**
  28552. * The green channel of this texture is multiplied against
  28553. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28554. *
  28555. * @type {?Texture}
  28556. * @default null
  28557. */
  28558. this.clearcoatRoughnessMap = null;
  28559. /**
  28560. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28561. * `(0,0)` to `(1,1)`.
  28562. *
  28563. * @type {Vector2}
  28564. * @default (1,1)
  28565. */
  28566. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28567. /**
  28568. * Can be used to enable independent normals for the clear coat layer.
  28569. *
  28570. * @type {?Texture}
  28571. * @default null
  28572. */
  28573. this.clearcoatNormalMap = null;
  28574. /**
  28575. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28576. *
  28577. * @type {number}
  28578. * @default 1.5
  28579. */
  28580. this.ior = 1.5;
  28581. /**
  28582. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28583. * corresponds to an index-of-refraction of `1.5`.
  28584. *
  28585. * This models the reflectivity of non-metallic materials. It has no effect
  28586. * when `metalness` is `1.0`
  28587. *
  28588. * @name MeshPhysicalMaterial#reflectivity
  28589. * @type {number}
  28590. * @default 0.5
  28591. */
  28592. Object.defineProperty( this, 'reflectivity', {
  28593. get: function () {
  28594. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28595. },
  28596. set: function ( reflectivity ) {
  28597. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28598. }
  28599. } );
  28600. /**
  28601. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28602. * control over iridescence.
  28603. *
  28604. * @type {?Texture}
  28605. * @default null
  28606. */
  28607. this.iridescenceMap = null;
  28608. /**
  28609. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28610. * Between `1.0` to `2.333`.
  28611. *
  28612. * @type {number}
  28613. * @default 1.3
  28614. */
  28615. this.iridescenceIOR = 1.3;
  28616. /**
  28617. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28618. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28619. *
  28620. * @type {Array<number,number>}
  28621. * @default [100,400]
  28622. */
  28623. this.iridescenceThicknessRange = [ 100, 400 ];
  28624. /**
  28625. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28626. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28627. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28628. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28629. * - Values in-between will linearly interpolate between the elements of the array.
  28630. *
  28631. * @type {?Texture}
  28632. * @default null
  28633. */
  28634. this.iridescenceThicknessMap = null;
  28635. /**
  28636. * The sheen tint.
  28637. *
  28638. * @type {Color}
  28639. * @default (0,0,0)
  28640. */
  28641. this.sheenColor = new Color( 0x000000 );
  28642. /**
  28643. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28644. * over sheen tint.
  28645. *
  28646. * @type {?Texture}
  28647. * @default null
  28648. */
  28649. this.sheenColorMap = null;
  28650. /**
  28651. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28652. *
  28653. * @type {number}
  28654. * @default 1
  28655. */
  28656. this.sheenRoughness = 1.0;
  28657. /**
  28658. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28659. * over sheen roughness.
  28660. *
  28661. * @type {?Texture}
  28662. * @default null
  28663. */
  28664. this.sheenRoughnessMap = null;
  28665. /**
  28666. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28667. * optical transparency.
  28668. *
  28669. * @type {?Texture}
  28670. * @default null
  28671. */
  28672. this.transmissionMap = null;
  28673. /**
  28674. * The thickness of the volume beneath the surface. The value is given in the
  28675. * coordinate space of the mesh. If the value is `0` the material is
  28676. * thin-walled. Otherwise the material is a volume boundary.
  28677. *
  28678. * @type {number}
  28679. * @default 0
  28680. */
  28681. this.thickness = 0;
  28682. /**
  28683. * A texture that defines the thickness, stored in the green channel. This will
  28684. * be multiplied by `thickness`.
  28685. *
  28686. * @type {?Texture}
  28687. * @default null
  28688. */
  28689. this.thicknessMap = null;
  28690. /**
  28691. * Density of the medium given as the average distance that light travels in
  28692. * the medium before interacting with a particle. The value is given in world
  28693. * space units, and must be greater than zero.
  28694. *
  28695. * @type {number}
  28696. * @default Infinity
  28697. */
  28698. this.attenuationDistance = Infinity;
  28699. /**
  28700. * The color that white light turns into due to absorption when reaching the
  28701. * attenuation distance.
  28702. *
  28703. * @type {Color}
  28704. * @default (1,1,1)
  28705. */
  28706. this.attenuationColor = new Color( 1, 1, 1 );
  28707. /**
  28708. * A float that scales the amount of specular reflection for non-metals only.
  28709. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28710. *
  28711. * @type {number}
  28712. * @default 1
  28713. */
  28714. this.specularIntensity = 1.0;
  28715. /**
  28716. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28717. * for per-pixel control over specular intensity.
  28718. *
  28719. * @type {?Texture}
  28720. * @default null
  28721. */
  28722. this.specularIntensityMap = null;
  28723. /**
  28724. * Tints the specular reflection at normal incidence for non-metals only.
  28725. *
  28726. * @type {Color}
  28727. * @default (1,1,1)
  28728. */
  28729. this.specularColor = new Color( 1, 1, 1 );
  28730. /**
  28731. * The RGB channels of this texture are multiplied against `specularColor`,
  28732. * for per-pixel control over specular color.
  28733. *
  28734. * @type {?Texture}
  28735. * @default null
  28736. */
  28737. this.specularColorMap = null;
  28738. this._anisotropy = 0;
  28739. this._clearcoat = 0;
  28740. this._dispersion = 0;
  28741. this._iridescence = 0;
  28742. this._sheen = 0.0;
  28743. this._transmission = 0;
  28744. this.setValues( parameters );
  28745. }
  28746. /**
  28747. * The anisotropy strength, from `0.0` to `1.0`.
  28748. *
  28749. * @type {number}
  28750. * @default 0
  28751. */
  28752. get anisotropy() {
  28753. return this._anisotropy;
  28754. }
  28755. set anisotropy( value ) {
  28756. if ( this._anisotropy > 0 !== value > 0 ) {
  28757. this.version ++;
  28758. }
  28759. this._anisotropy = value;
  28760. }
  28761. /**
  28762. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28763. * clear coat related properties to enable multilayer materials that have a
  28764. * thin translucent layer over the base layer.
  28765. *
  28766. * @type {number}
  28767. * @default 0
  28768. */
  28769. get clearcoat() {
  28770. return this._clearcoat;
  28771. }
  28772. set clearcoat( value ) {
  28773. if ( this._clearcoat > 0 !== value > 0 ) {
  28774. this.version ++;
  28775. }
  28776. this._clearcoat = value;
  28777. }
  28778. /**
  28779. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28780. * the surface and the viewer, from `0.0` to `1.0`.
  28781. *
  28782. * @type {number}
  28783. * @default 0
  28784. */
  28785. get iridescence() {
  28786. return this._iridescence;
  28787. }
  28788. set iridescence( value ) {
  28789. if ( this._iridescence > 0 !== value > 0 ) {
  28790. this.version ++;
  28791. }
  28792. this._iridescence = value;
  28793. }
  28794. /**
  28795. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28796. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28797. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28798. *
  28799. * @type {number}
  28800. * @default 0
  28801. */
  28802. get dispersion() {
  28803. return this._dispersion;
  28804. }
  28805. set dispersion( value ) {
  28806. if ( this._dispersion > 0 !== value > 0 ) {
  28807. this.version ++;
  28808. }
  28809. this._dispersion = value;
  28810. }
  28811. /**
  28812. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28813. *
  28814. * @type {number}
  28815. * @default 0
  28816. */
  28817. get sheen() {
  28818. return this._sheen;
  28819. }
  28820. set sheen( value ) {
  28821. if ( this._sheen > 0 !== value > 0 ) {
  28822. this.version ++;
  28823. }
  28824. this._sheen = value;
  28825. }
  28826. /**
  28827. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28828. *
  28829. * Thin, transparent or semitransparent, plastic or glass materials remain
  28830. * largely reflective even if they are fully transmissive. The transmission
  28831. * property can be used to model these materials.
  28832. *
  28833. * When transmission is non-zero, `opacity` should be set to `1`.
  28834. *
  28835. * @type {number}
  28836. * @default 0
  28837. */
  28838. get transmission() {
  28839. return this._transmission;
  28840. }
  28841. set transmission( value ) {
  28842. if ( this._transmission > 0 !== value > 0 ) {
  28843. this.version ++;
  28844. }
  28845. this._transmission = value;
  28846. }
  28847. copy( source ) {
  28848. super.copy( source );
  28849. this.defines = {
  28850. 'STANDARD': '',
  28851. 'PHYSICAL': ''
  28852. };
  28853. this.anisotropy = source.anisotropy;
  28854. this.anisotropyRotation = source.anisotropyRotation;
  28855. this.anisotropyMap = source.anisotropyMap;
  28856. this.clearcoat = source.clearcoat;
  28857. this.clearcoatMap = source.clearcoatMap;
  28858. this.clearcoatRoughness = source.clearcoatRoughness;
  28859. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28860. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28861. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28862. this.dispersion = source.dispersion;
  28863. this.ior = source.ior;
  28864. this.iridescence = source.iridescence;
  28865. this.iridescenceMap = source.iridescenceMap;
  28866. this.iridescenceIOR = source.iridescenceIOR;
  28867. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28868. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28869. this.sheen = source.sheen;
  28870. this.sheenColor.copy( source.sheenColor );
  28871. this.sheenColorMap = source.sheenColorMap;
  28872. this.sheenRoughness = source.sheenRoughness;
  28873. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28874. this.transmission = source.transmission;
  28875. this.transmissionMap = source.transmissionMap;
  28876. this.thickness = source.thickness;
  28877. this.thicknessMap = source.thicknessMap;
  28878. this.attenuationDistance = source.attenuationDistance;
  28879. this.attenuationColor.copy( source.attenuationColor );
  28880. this.specularIntensity = source.specularIntensity;
  28881. this.specularIntensityMap = source.specularIntensityMap;
  28882. this.specularColor.copy( source.specularColor );
  28883. this.specularColorMap = source.specularColorMap;
  28884. return this;
  28885. }
  28886. }
  28887. /**
  28888. * A material for shiny surfaces with specular highlights.
  28889. *
  28890. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28891. * model for calculating reflectance. Unlike the Lambertian model used in the
  28892. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28893. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28894. *
  28895. * Performance will generally be greater when using this material over the
  28896. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28897. * some graphical accuracy.
  28898. *
  28899. * @augments Material
  28900. * @demo scenes/material-browser.html#MeshPhongMaterial
  28901. */
  28902. class MeshPhongMaterial extends Material {
  28903. /**
  28904. * Constructs a new mesh phong material.
  28905. *
  28906. * @param {Object} [parameters] - An object with one or more properties
  28907. * defining the material's appearance. Any property of the material
  28908. * (including any property from inherited materials) can be passed
  28909. * in here. Color values can be passed any type of value accepted
  28910. * by {@link Color#set}.
  28911. */
  28912. constructor( parameters ) {
  28913. super();
  28914. /**
  28915. * This flag can be used for type testing.
  28916. *
  28917. * @type {boolean}
  28918. * @readonly
  28919. * @default true
  28920. */
  28921. this.isMeshPhongMaterial = true;
  28922. this.type = 'MeshPhongMaterial';
  28923. /**
  28924. * Color of the material.
  28925. *
  28926. * @type {Color}
  28927. * @default (1,1,1)
  28928. */
  28929. this.color = new Color( 0xffffff ); // diffuse
  28930. /**
  28931. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28932. *
  28933. * This defines how shiny the material is and the color of its shine.
  28934. *
  28935. * @type {Color}
  28936. */
  28937. this.specular = new Color( 0x111111 );
  28938. /**
  28939. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28940. *
  28941. * @type {number}
  28942. * @default 30
  28943. */
  28944. this.shininess = 30;
  28945. /**
  28946. * The color map. May optionally include an alpha channel, typically combined
  28947. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28948. * color is modulated by the diffuse `color`.
  28949. *
  28950. * @type {?Texture}
  28951. * @default null
  28952. */
  28953. this.map = null;
  28954. /**
  28955. * The light map. Requires a second set of UVs.
  28956. *
  28957. * @type {?Texture}
  28958. * @default null
  28959. */
  28960. this.lightMap = null;
  28961. /**
  28962. * Intensity of the baked light.
  28963. *
  28964. * @type {number}
  28965. * @default 1
  28966. */
  28967. this.lightMapIntensity = 1.0;
  28968. /**
  28969. * The red channel of this texture is used as the ambient occlusion map.
  28970. * Requires a second set of UVs.
  28971. *
  28972. * @type {?Texture}
  28973. * @default null
  28974. */
  28975. this.aoMap = null;
  28976. /**
  28977. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28978. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28979. * red channel is also `1`, ambient light is fully occluded on a surface.
  28980. *
  28981. * @type {number}
  28982. * @default 1
  28983. */
  28984. this.aoMapIntensity = 1.0;
  28985. /**
  28986. * Emissive (light) color of the material, essentially a solid color
  28987. * unaffected by other lighting.
  28988. *
  28989. * @type {Color}
  28990. * @default (0,0,0)
  28991. */
  28992. this.emissive = new Color( 0x000000 );
  28993. /**
  28994. * Intensity of the emissive light. Modulates the emissive color.
  28995. *
  28996. * @type {number}
  28997. * @default 1
  28998. */
  28999. this.emissiveIntensity = 1.0;
  29000. /**
  29001. * Set emissive (glow) map. The emissive map color is modulated by the
  29002. * emissive color and the emissive intensity. If you have an emissive map,
  29003. * be sure to set the emissive color to something other than black.
  29004. *
  29005. * @type {?Texture}
  29006. * @default null
  29007. */
  29008. this.emissiveMap = null;
  29009. /**
  29010. * The texture to create a bump map. The black and white values map to the
  29011. * perceived depth in relation to the lights. Bump doesn't actually affect
  29012. * the geometry of the object, only the lighting. If a normal map is defined
  29013. * this will be ignored.
  29014. *
  29015. * @type {?Texture}
  29016. * @default null
  29017. */
  29018. this.bumpMap = null;
  29019. /**
  29020. * How much the bump map affects the material. Typical range is `[0,1]`.
  29021. *
  29022. * @type {number}
  29023. * @default 1
  29024. */
  29025. this.bumpScale = 1;
  29026. /**
  29027. * The texture to create a normal map. The RGB values affect the surface
  29028. * normal for each pixel fragment and change the way the color is lit. Normal
  29029. * maps do not change the actual shape of the surface, only the lighting. In
  29030. * case the material has a normal map authored using the left handed
  29031. * convention, the `y` component of `normalScale` should be negated to compensate
  29032. * for the different handedness.
  29033. *
  29034. * @type {?Texture}
  29035. * @default null
  29036. */
  29037. this.normalMap = null;
  29038. /**
  29039. * The type of normal map.
  29040. *
  29041. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29042. * @default TangentSpaceNormalMap
  29043. */
  29044. this.normalMapType = TangentSpaceNormalMap;
  29045. /**
  29046. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29047. *
  29048. * @type {Vector2}
  29049. * @default (1,1)
  29050. */
  29051. this.normalScale = new Vector2( 1, 1 );
  29052. /**
  29053. * The displacement map affects the position of the mesh's vertices. Unlike
  29054. * other maps which only affect the light and shade of the material the
  29055. * displaced vertices can cast shadows, block other objects, and otherwise
  29056. * act as real geometry. The displacement texture is an image where the value
  29057. * of each pixel (white being the highest) is mapped against, and
  29058. * repositions, the vertices of the mesh.
  29059. *
  29060. * @type {?Texture}
  29061. * @default null
  29062. */
  29063. this.displacementMap = null;
  29064. /**
  29065. * How much the displacement map affects the mesh (where black is no
  29066. * displacement, and white is maximum displacement). Without a displacement
  29067. * map set, this value is not applied.
  29068. *
  29069. * @type {number}
  29070. * @default 0
  29071. */
  29072. this.displacementScale = 1;
  29073. /**
  29074. * The offset of the displacement map's values on the mesh's vertices.
  29075. * The bias is added to the scaled sample of the displacement map.
  29076. * Without a displacement map set, this value is not applied.
  29077. *
  29078. * @type {number}
  29079. * @default 0
  29080. */
  29081. this.displacementBias = 0;
  29082. /**
  29083. * The specular map value affects both how much the specular surface
  29084. * highlight contributes and how much of the environment map affects the
  29085. * surface.
  29086. *
  29087. * @type {?Texture}
  29088. * @default null
  29089. */
  29090. this.specularMap = null;
  29091. /**
  29092. * The alpha map is a grayscale texture that controls the opacity across the
  29093. * surface (black: fully transparent; white: fully opaque).
  29094. *
  29095. * Only the color of the texture is used, ignoring the alpha channel if one
  29096. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29097. * when sampling this texture due to the extra bit of precision provided for
  29098. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29099. * luminance/alpha textures will also still work as expected.
  29100. *
  29101. * @type {?Texture}
  29102. * @default null
  29103. */
  29104. this.alphaMap = null;
  29105. /**
  29106. * The environment map.
  29107. *
  29108. * @type {?Texture}
  29109. * @default null
  29110. */
  29111. this.envMap = null;
  29112. /**
  29113. * The rotation of the environment map in radians.
  29114. *
  29115. * @type {Euler}
  29116. * @default (0,0,0)
  29117. */
  29118. this.envMapRotation = new Euler();
  29119. /**
  29120. * How to combine the result of the surface's color with the environment map, if any.
  29121. *
  29122. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29123. * blend between the two colors.
  29124. *
  29125. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29126. * @default MultiplyOperation
  29127. */
  29128. this.combine = MultiplyOperation;
  29129. /**
  29130. * How much the environment map affects the surface.
  29131. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29132. *
  29133. * @type {number}
  29134. * @default 1
  29135. */
  29136. this.reflectivity = 1;
  29137. /**
  29138. * Scales the effect of the environment map by multiplying its color.
  29139. *
  29140. * @type {number}
  29141. * @default 1
  29142. */
  29143. this.envMapIntensity = 1.0;
  29144. /**
  29145. * The index of refraction (IOR) of air (approximately 1) divided by the
  29146. * index of refraction of the material. It is used with environment mapping
  29147. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29148. * The refraction ratio should not exceed `1`.
  29149. *
  29150. * @type {number}
  29151. * @default 0.98
  29152. */
  29153. this.refractionRatio = 0.98;
  29154. /**
  29155. * Renders the geometry as a wireframe.
  29156. *
  29157. * @type {boolean}
  29158. * @default false
  29159. */
  29160. this.wireframe = false;
  29161. /**
  29162. * Controls the thickness of the wireframe.
  29163. *
  29164. * Can only be used with {@link SVGRenderer}.
  29165. *
  29166. * @type {number}
  29167. * @default 1
  29168. */
  29169. this.wireframeLinewidth = 1;
  29170. /**
  29171. * Defines appearance of wireframe ends.
  29172. *
  29173. * Can only be used with {@link SVGRenderer}.
  29174. *
  29175. * @type {('round'|'bevel'|'miter')}
  29176. * @default 'round'
  29177. */
  29178. this.wireframeLinecap = 'round';
  29179. /**
  29180. * Defines appearance of wireframe joints.
  29181. *
  29182. * Can only be used with {@link SVGRenderer}.
  29183. *
  29184. * @type {('round'|'bevel'|'miter')}
  29185. * @default 'round'
  29186. */
  29187. this.wireframeLinejoin = 'round';
  29188. /**
  29189. * Whether the material is rendered with flat shading or not.
  29190. *
  29191. * @type {boolean}
  29192. * @default false
  29193. */
  29194. this.flatShading = false;
  29195. /**
  29196. * Whether the material is affected by fog or not.
  29197. *
  29198. * @type {boolean}
  29199. * @default true
  29200. */
  29201. this.fog = true;
  29202. this.setValues( parameters );
  29203. }
  29204. copy( source ) {
  29205. super.copy( source );
  29206. this.color.copy( source.color );
  29207. this.specular.copy( source.specular );
  29208. this.shininess = source.shininess;
  29209. this.map = source.map;
  29210. this.lightMap = source.lightMap;
  29211. this.lightMapIntensity = source.lightMapIntensity;
  29212. this.aoMap = source.aoMap;
  29213. this.aoMapIntensity = source.aoMapIntensity;
  29214. this.emissive.copy( source.emissive );
  29215. this.emissiveMap = source.emissiveMap;
  29216. this.emissiveIntensity = source.emissiveIntensity;
  29217. this.bumpMap = source.bumpMap;
  29218. this.bumpScale = source.bumpScale;
  29219. this.normalMap = source.normalMap;
  29220. this.normalMapType = source.normalMapType;
  29221. this.normalScale.copy( source.normalScale );
  29222. this.displacementMap = source.displacementMap;
  29223. this.displacementScale = source.displacementScale;
  29224. this.displacementBias = source.displacementBias;
  29225. this.specularMap = source.specularMap;
  29226. this.alphaMap = source.alphaMap;
  29227. this.envMap = source.envMap;
  29228. this.envMapRotation.copy( source.envMapRotation );
  29229. this.combine = source.combine;
  29230. this.reflectivity = source.reflectivity;
  29231. this.envMapIntensity = source.envMapIntensity;
  29232. this.refractionRatio = source.refractionRatio;
  29233. this.wireframe = source.wireframe;
  29234. this.wireframeLinewidth = source.wireframeLinewidth;
  29235. this.wireframeLinecap = source.wireframeLinecap;
  29236. this.wireframeLinejoin = source.wireframeLinejoin;
  29237. this.flatShading = source.flatShading;
  29238. this.fog = source.fog;
  29239. return this;
  29240. }
  29241. }
  29242. /**
  29243. * A material implementing toon shading.
  29244. *
  29245. * @augments Material
  29246. * @demo scenes/material-browser.html#MeshToonMaterial
  29247. */
  29248. class MeshToonMaterial extends Material {
  29249. /**
  29250. * Constructs a new mesh toon material.
  29251. *
  29252. * @param {Object} [parameters] - An object with one or more properties
  29253. * defining the material's appearance. Any property of the material
  29254. * (including any property from inherited materials) can be passed
  29255. * in here. Color values can be passed any type of value accepted
  29256. * by {@link Color#set}.
  29257. */
  29258. constructor( parameters ) {
  29259. super();
  29260. /**
  29261. * This flag can be used for type testing.
  29262. *
  29263. * @type {boolean}
  29264. * @readonly
  29265. * @default true
  29266. */
  29267. this.isMeshToonMaterial = true;
  29268. this.defines = { 'TOON': '' };
  29269. this.type = 'MeshToonMaterial';
  29270. /**
  29271. * Color of the material.
  29272. *
  29273. * @type {Color}
  29274. * @default (1,1,1)
  29275. */
  29276. this.color = new Color( 0xffffff );
  29277. /**
  29278. * The color map. May optionally include an alpha channel, typically combined
  29279. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29280. * color is modulated by the diffuse `color`.
  29281. *
  29282. * @type {?Texture}
  29283. * @default null
  29284. */
  29285. this.map = null;
  29286. /**
  29287. * Gradient map for toon shading. It's required to set
  29288. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  29289. * when using this type of texture.
  29290. *
  29291. * @type {?Texture}
  29292. * @default null
  29293. */
  29294. this.gradientMap = null;
  29295. /**
  29296. * The light map. Requires a second set of UVs.
  29297. *
  29298. * @type {?Texture}
  29299. * @default null
  29300. */
  29301. this.lightMap = null;
  29302. /**
  29303. * Intensity of the baked light.
  29304. *
  29305. * @type {number}
  29306. * @default 1
  29307. */
  29308. this.lightMapIntensity = 1.0;
  29309. /**
  29310. * The red channel of this texture is used as the ambient occlusion map.
  29311. * Requires a second set of UVs.
  29312. *
  29313. * @type {?Texture}
  29314. * @default null
  29315. */
  29316. this.aoMap = null;
  29317. /**
  29318. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29319. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29320. * red channel is also `1`, ambient light is fully occluded on a surface.
  29321. *
  29322. * @type {number}
  29323. * @default 1
  29324. */
  29325. this.aoMapIntensity = 1.0;
  29326. /**
  29327. * Emissive (light) color of the material, essentially a solid color
  29328. * unaffected by other lighting.
  29329. *
  29330. * @type {Color}
  29331. * @default (0,0,0)
  29332. */
  29333. this.emissive = new Color( 0x000000 );
  29334. /**
  29335. * Intensity of the emissive light. Modulates the emissive color.
  29336. *
  29337. * @type {number}
  29338. * @default 1
  29339. */
  29340. this.emissiveIntensity = 1.0;
  29341. /**
  29342. * Set emissive (glow) map. The emissive map color is modulated by the
  29343. * emissive color and the emissive intensity. If you have an emissive map,
  29344. * be sure to set the emissive color to something other than black.
  29345. *
  29346. * @type {?Texture}
  29347. * @default null
  29348. */
  29349. this.emissiveMap = null;
  29350. /**
  29351. * The texture to create a bump map. The black and white values map to the
  29352. * perceived depth in relation to the lights. Bump doesn't actually affect
  29353. * the geometry of the object, only the lighting. If a normal map is defined
  29354. * this will be ignored.
  29355. *
  29356. * @type {?Texture}
  29357. * @default null
  29358. */
  29359. this.bumpMap = null;
  29360. /**
  29361. * How much the bump map affects the material. Typical range is `[0,1]`.
  29362. *
  29363. * @type {number}
  29364. * @default 1
  29365. */
  29366. this.bumpScale = 1;
  29367. /**
  29368. * The texture to create a normal map. The RGB values affect the surface
  29369. * normal for each pixel fragment and change the way the color is lit. Normal
  29370. * maps do not change the actual shape of the surface, only the lighting. In
  29371. * case the material has a normal map authored using the left handed
  29372. * convention, the `y` component of `normalScale` should be negated to compensate
  29373. * for the different handedness.
  29374. *
  29375. * @type {?Texture}
  29376. * @default null
  29377. */
  29378. this.normalMap = null;
  29379. /**
  29380. * The type of normal map.
  29381. *
  29382. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29383. * @default TangentSpaceNormalMap
  29384. */
  29385. this.normalMapType = TangentSpaceNormalMap;
  29386. /**
  29387. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29388. *
  29389. * @type {Vector2}
  29390. * @default (1,1)
  29391. */
  29392. this.normalScale = new Vector2( 1, 1 );
  29393. /**
  29394. * The displacement map affects the position of the mesh's vertices. Unlike
  29395. * other maps which only affect the light and shade of the material the
  29396. * displaced vertices can cast shadows, block other objects, and otherwise
  29397. * act as real geometry. The displacement texture is an image where the value
  29398. * of each pixel (white being the highest) is mapped against, and
  29399. * repositions, the vertices of the mesh.
  29400. *
  29401. * @type {?Texture}
  29402. * @default null
  29403. */
  29404. this.displacementMap = null;
  29405. /**
  29406. * How much the displacement map affects the mesh (where black is no
  29407. * displacement, and white is maximum displacement). Without a displacement
  29408. * map set, this value is not applied.
  29409. *
  29410. * @type {number}
  29411. * @default 0
  29412. */
  29413. this.displacementScale = 1;
  29414. /**
  29415. * The offset of the displacement map's values on the mesh's vertices.
  29416. * The bias is added to the scaled sample of the displacement map.
  29417. * Without a displacement map set, this value is not applied.
  29418. *
  29419. * @type {number}
  29420. * @default 0
  29421. */
  29422. this.displacementBias = 0;
  29423. /**
  29424. * The alpha map is a grayscale texture that controls the opacity across the
  29425. * surface (black: fully transparent; white: fully opaque).
  29426. *
  29427. * Only the color of the texture is used, ignoring the alpha channel if one
  29428. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29429. * when sampling this texture due to the extra bit of precision provided for
  29430. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29431. * luminance/alpha textures will also still work as expected.
  29432. *
  29433. * @type {?Texture}
  29434. * @default null
  29435. */
  29436. this.alphaMap = null;
  29437. /**
  29438. * Renders the geometry as a wireframe.
  29439. *
  29440. * @type {boolean}
  29441. * @default false
  29442. */
  29443. this.wireframe = false;
  29444. /**
  29445. * Controls the thickness of the wireframe.
  29446. *
  29447. * Can only be used with {@link SVGRenderer}.
  29448. *
  29449. * @type {number}
  29450. * @default 1
  29451. */
  29452. this.wireframeLinewidth = 1;
  29453. /**
  29454. * Defines appearance of wireframe ends.
  29455. *
  29456. * Can only be used with {@link SVGRenderer}.
  29457. *
  29458. * @type {('round'|'bevel'|'miter')}
  29459. * @default 'round'
  29460. */
  29461. this.wireframeLinecap = 'round';
  29462. /**
  29463. * Defines appearance of wireframe joints.
  29464. *
  29465. * Can only be used with {@link SVGRenderer}.
  29466. *
  29467. * @type {('round'|'bevel'|'miter')}
  29468. * @default 'round'
  29469. */
  29470. this.wireframeLinejoin = 'round';
  29471. /**
  29472. * Whether the material is affected by fog or not.
  29473. *
  29474. * @type {boolean}
  29475. * @default true
  29476. */
  29477. this.fog = true;
  29478. this.setValues( parameters );
  29479. }
  29480. copy( source ) {
  29481. super.copy( source );
  29482. this.color.copy( source.color );
  29483. this.map = source.map;
  29484. this.gradientMap = source.gradientMap;
  29485. this.lightMap = source.lightMap;
  29486. this.lightMapIntensity = source.lightMapIntensity;
  29487. this.aoMap = source.aoMap;
  29488. this.aoMapIntensity = source.aoMapIntensity;
  29489. this.emissive.copy( source.emissive );
  29490. this.emissiveMap = source.emissiveMap;
  29491. this.emissiveIntensity = source.emissiveIntensity;
  29492. this.bumpMap = source.bumpMap;
  29493. this.bumpScale = source.bumpScale;
  29494. this.normalMap = source.normalMap;
  29495. this.normalMapType = source.normalMapType;
  29496. this.normalScale.copy( source.normalScale );
  29497. this.displacementMap = source.displacementMap;
  29498. this.displacementScale = source.displacementScale;
  29499. this.displacementBias = source.displacementBias;
  29500. this.alphaMap = source.alphaMap;
  29501. this.wireframe = source.wireframe;
  29502. this.wireframeLinewidth = source.wireframeLinewidth;
  29503. this.wireframeLinecap = source.wireframeLinecap;
  29504. this.wireframeLinejoin = source.wireframeLinejoin;
  29505. this.fog = source.fog;
  29506. return this;
  29507. }
  29508. }
  29509. /**
  29510. * A material that maps the normal vectors to RGB colors.
  29511. *
  29512. * @augments Material
  29513. * @demo scenes/material-browser.html#MeshNormalMaterial
  29514. */
  29515. class MeshNormalMaterial extends Material {
  29516. /**
  29517. * Constructs a new mesh normal material.
  29518. *
  29519. * @param {Object} [parameters] - An object with one or more properties
  29520. * defining the material's appearance. Any property of the material
  29521. * (including any property from inherited materials) can be passed
  29522. * in here. Color values can be passed any type of value accepted
  29523. * by {@link Color#set}.
  29524. */
  29525. constructor( parameters ) {
  29526. super();
  29527. /**
  29528. * This flag can be used for type testing.
  29529. *
  29530. * @type {boolean}
  29531. * @readonly
  29532. * @default true
  29533. */
  29534. this.isMeshNormalMaterial = true;
  29535. this.type = 'MeshNormalMaterial';
  29536. /**
  29537. * The texture to create a bump map. The black and white values map to the
  29538. * perceived depth in relation to the lights. Bump doesn't actually affect
  29539. * the geometry of the object, only the lighting. If a normal map is defined
  29540. * this will be ignored.
  29541. *
  29542. * @type {?Texture}
  29543. * @default null
  29544. */
  29545. this.bumpMap = null;
  29546. /**
  29547. * How much the bump map affects the material. Typical range is `[0,1]`.
  29548. *
  29549. * @type {number}
  29550. * @default 1
  29551. */
  29552. this.bumpScale = 1;
  29553. /**
  29554. * The texture to create a normal map. The RGB values affect the surface
  29555. * normal for each pixel fragment and change the way the color is lit. Normal
  29556. * maps do not change the actual shape of the surface, only the lighting. In
  29557. * case the material has a normal map authored using the left handed
  29558. * convention, the `y` component of `normalScale` should be negated to compensate
  29559. * for the different handedness.
  29560. *
  29561. * @type {?Texture}
  29562. * @default null
  29563. */
  29564. this.normalMap = null;
  29565. /**
  29566. * The type of normal map.
  29567. *
  29568. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29569. * @default TangentSpaceNormalMap
  29570. */
  29571. this.normalMapType = TangentSpaceNormalMap;
  29572. /**
  29573. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29574. *
  29575. * @type {Vector2}
  29576. * @default (1,1)
  29577. */
  29578. this.normalScale = new Vector2( 1, 1 );
  29579. /**
  29580. * The displacement map affects the position of the mesh's vertices. Unlike
  29581. * other maps which only affect the light and shade of the material the
  29582. * displaced vertices can cast shadows, block other objects, and otherwise
  29583. * act as real geometry. The displacement texture is an image where the value
  29584. * of each pixel (white being the highest) is mapped against, and
  29585. * repositions, the vertices of the mesh.
  29586. *
  29587. * @type {?Texture}
  29588. * @default null
  29589. */
  29590. this.displacementMap = null;
  29591. /**
  29592. * How much the displacement map affects the mesh (where black is no
  29593. * displacement, and white is maximum displacement). Without a displacement
  29594. * map set, this value is not applied.
  29595. *
  29596. * @type {number}
  29597. * @default 0
  29598. */
  29599. this.displacementScale = 1;
  29600. /**
  29601. * The offset of the displacement map's values on the mesh's vertices.
  29602. * The bias is added to the scaled sample of the displacement map.
  29603. * Without a displacement map set, this value is not applied.
  29604. *
  29605. * @type {number}
  29606. * @default 0
  29607. */
  29608. this.displacementBias = 0;
  29609. /**
  29610. * Renders the geometry as a wireframe.
  29611. *
  29612. * @type {boolean}
  29613. * @default false
  29614. */
  29615. this.wireframe = false;
  29616. /**
  29617. * Controls the thickness of the wireframe.
  29618. *
  29619. * WebGL and WebGPU ignore this property and always render
  29620. * 1 pixel wide lines.
  29621. *
  29622. * @type {number}
  29623. * @default 1
  29624. */
  29625. this.wireframeLinewidth = 1;
  29626. /**
  29627. * Whether the material is rendered with flat shading or not.
  29628. *
  29629. * @type {boolean}
  29630. * @default false
  29631. */
  29632. this.flatShading = false;
  29633. this.setValues( parameters );
  29634. }
  29635. copy( source ) {
  29636. super.copy( source );
  29637. this.bumpMap = source.bumpMap;
  29638. this.bumpScale = source.bumpScale;
  29639. this.normalMap = source.normalMap;
  29640. this.normalMapType = source.normalMapType;
  29641. this.normalScale.copy( source.normalScale );
  29642. this.displacementMap = source.displacementMap;
  29643. this.displacementScale = source.displacementScale;
  29644. this.displacementBias = source.displacementBias;
  29645. this.wireframe = source.wireframe;
  29646. this.wireframeLinewidth = source.wireframeLinewidth;
  29647. this.flatShading = source.flatShading;
  29648. return this;
  29649. }
  29650. }
  29651. /**
  29652. * A material for non-shiny surfaces, without specular highlights.
  29653. *
  29654. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29655. * model for calculating reflectance. This can simulate some surfaces (such
  29656. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29657. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29658. * shading.
  29659. *
  29660. * Due to the simplicity of the reflectance and illumination models,
  29661. * performance will be greater when using this material over the
  29662. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29663. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29664. *
  29665. * @augments Material
  29666. * @demo scenes/material-browser.html#MeshLambertMaterial
  29667. */
  29668. class MeshLambertMaterial extends Material {
  29669. /**
  29670. * Constructs a new mesh lambert material.
  29671. *
  29672. * @param {Object} [parameters] - An object with one or more properties
  29673. * defining the material's appearance. Any property of the material
  29674. * (including any property from inherited materials) can be passed
  29675. * in here. Color values can be passed any type of value accepted
  29676. * by {@link Color#set}.
  29677. */
  29678. constructor( parameters ) {
  29679. super();
  29680. /**
  29681. * This flag can be used for type testing.
  29682. *
  29683. * @type {boolean}
  29684. * @readonly
  29685. * @default true
  29686. */
  29687. this.isMeshLambertMaterial = true;
  29688. this.type = 'MeshLambertMaterial';
  29689. /**
  29690. * Color of the material.
  29691. *
  29692. * @type {Color}
  29693. * @default (1,1,1)
  29694. */
  29695. this.color = new Color( 0xffffff ); // diffuse
  29696. /**
  29697. * The color map. May optionally include an alpha channel, typically combined
  29698. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29699. * color is modulated by the diffuse `color`.
  29700. *
  29701. * @type {?Texture}
  29702. * @default null
  29703. */
  29704. this.map = null;
  29705. /**
  29706. * The light map. Requires a second set of UVs.
  29707. *
  29708. * @type {?Texture}
  29709. * @default null
  29710. */
  29711. this.lightMap = null;
  29712. /**
  29713. * Intensity of the baked light.
  29714. *
  29715. * @type {number}
  29716. * @default 1
  29717. */
  29718. this.lightMapIntensity = 1.0;
  29719. /**
  29720. * The red channel of this texture is used as the ambient occlusion map.
  29721. * Requires a second set of UVs.
  29722. *
  29723. * @type {?Texture}
  29724. * @default null
  29725. */
  29726. this.aoMap = null;
  29727. /**
  29728. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29729. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29730. * red channel is also `1`, ambient light is fully occluded on a surface.
  29731. *
  29732. * @type {number}
  29733. * @default 1
  29734. */
  29735. this.aoMapIntensity = 1.0;
  29736. /**
  29737. * Emissive (light) color of the material, essentially a solid color
  29738. * unaffected by other lighting.
  29739. *
  29740. * @type {Color}
  29741. * @default (0,0,0)
  29742. */
  29743. this.emissive = new Color( 0x000000 );
  29744. /**
  29745. * Intensity of the emissive light. Modulates the emissive color.
  29746. *
  29747. * @type {number}
  29748. * @default 1
  29749. */
  29750. this.emissiveIntensity = 1.0;
  29751. /**
  29752. * Set emissive (glow) map. The emissive map color is modulated by the
  29753. * emissive color and the emissive intensity. If you have an emissive map,
  29754. * be sure to set the emissive color to something other than black.
  29755. *
  29756. * @type {?Texture}
  29757. * @default null
  29758. */
  29759. this.emissiveMap = null;
  29760. /**
  29761. * The texture to create a bump map. The black and white values map to the
  29762. * perceived depth in relation to the lights. Bump doesn't actually affect
  29763. * the geometry of the object, only the lighting. If a normal map is defined
  29764. * this will be ignored.
  29765. *
  29766. * @type {?Texture}
  29767. * @default null
  29768. */
  29769. this.bumpMap = null;
  29770. /**
  29771. * How much the bump map affects the material. Typical range is `[0,1]`.
  29772. *
  29773. * @type {number}
  29774. * @default 1
  29775. */
  29776. this.bumpScale = 1;
  29777. /**
  29778. * The texture to create a normal map. The RGB values affect the surface
  29779. * normal for each pixel fragment and change the way the color is lit. Normal
  29780. * maps do not change the actual shape of the surface, only the lighting. In
  29781. * case the material has a normal map authored using the left handed
  29782. * convention, the `y` component of `normalScale` should be negated to compensate
  29783. * for the different handedness.
  29784. *
  29785. * @type {?Texture}
  29786. * @default null
  29787. */
  29788. this.normalMap = null;
  29789. /**
  29790. * The type of normal map.
  29791. *
  29792. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29793. * @default TangentSpaceNormalMap
  29794. */
  29795. this.normalMapType = TangentSpaceNormalMap;
  29796. /**
  29797. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29798. *
  29799. * @type {Vector2}
  29800. * @default (1,1)
  29801. */
  29802. this.normalScale = new Vector2( 1, 1 );
  29803. /**
  29804. * The displacement map affects the position of the mesh's vertices. Unlike
  29805. * other maps which only affect the light and shade of the material the
  29806. * displaced vertices can cast shadows, block other objects, and otherwise
  29807. * act as real geometry. The displacement texture is an image where the value
  29808. * of each pixel (white being the highest) is mapped against, and
  29809. * repositions, the vertices of the mesh.
  29810. *
  29811. * @type {?Texture}
  29812. * @default null
  29813. */
  29814. this.displacementMap = null;
  29815. /**
  29816. * How much the displacement map affects the mesh (where black is no
  29817. * displacement, and white is maximum displacement). Without a displacement
  29818. * map set, this value is not applied.
  29819. *
  29820. * @type {number}
  29821. * @default 0
  29822. */
  29823. this.displacementScale = 1;
  29824. /**
  29825. * The offset of the displacement map's values on the mesh's vertices.
  29826. * The bias is added to the scaled sample of the displacement map.
  29827. * Without a displacement map set, this value is not applied.
  29828. *
  29829. * @type {number}
  29830. * @default 0
  29831. */
  29832. this.displacementBias = 0;
  29833. /**
  29834. * Specular map used by the material.
  29835. *
  29836. * @type {?Texture}
  29837. * @default null
  29838. */
  29839. this.specularMap = null;
  29840. /**
  29841. * The alpha map is a grayscale texture that controls the opacity across the
  29842. * surface (black: fully transparent; white: fully opaque).
  29843. *
  29844. * Only the color of the texture is used, ignoring the alpha channel if one
  29845. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29846. * when sampling this texture due to the extra bit of precision provided for
  29847. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29848. * luminance/alpha textures will also still work as expected.
  29849. *
  29850. * @type {?Texture}
  29851. * @default null
  29852. */
  29853. this.alphaMap = null;
  29854. /**
  29855. * The environment map.
  29856. *
  29857. * @type {?Texture}
  29858. * @default null
  29859. */
  29860. this.envMap = null;
  29861. /**
  29862. * The rotation of the environment map in radians.
  29863. *
  29864. * @type {Euler}
  29865. * @default (0,0,0)
  29866. */
  29867. this.envMapRotation = new Euler();
  29868. /**
  29869. * How to combine the result of the surface's color with the environment map, if any.
  29870. *
  29871. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29872. * blend between the two colors.
  29873. *
  29874. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29875. * @default MultiplyOperation
  29876. */
  29877. this.combine = MultiplyOperation;
  29878. /**
  29879. * How much the environment map affects the surface.
  29880. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29881. *
  29882. * @type {number}
  29883. * @default 1
  29884. */
  29885. this.reflectivity = 1;
  29886. /**
  29887. * Scales the effect of the environment map by multiplying its color.
  29888. *
  29889. * @type {number}
  29890. * @default 1
  29891. */
  29892. this.envMapIntensity = 1.0;
  29893. /**
  29894. * The index of refraction (IOR) of air (approximately 1) divided by the
  29895. * index of refraction of the material. It is used with environment mapping
  29896. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29897. * The refraction ratio should not exceed `1`.
  29898. *
  29899. * @type {number}
  29900. * @default 0.98
  29901. */
  29902. this.refractionRatio = 0.98;
  29903. /**
  29904. * Renders the geometry as a wireframe.
  29905. *
  29906. * @type {boolean}
  29907. * @default false
  29908. */
  29909. this.wireframe = false;
  29910. /**
  29911. * Controls the thickness of the wireframe.
  29912. *
  29913. * Can only be used with {@link SVGRenderer}.
  29914. *
  29915. * @type {number}
  29916. * @default 1
  29917. */
  29918. this.wireframeLinewidth = 1;
  29919. /**
  29920. * Defines appearance of wireframe ends.
  29921. *
  29922. * Can only be used with {@link SVGRenderer}.
  29923. *
  29924. * @type {('round'|'bevel'|'miter')}
  29925. * @default 'round'
  29926. */
  29927. this.wireframeLinecap = 'round';
  29928. /**
  29929. * Defines appearance of wireframe joints.
  29930. *
  29931. * Can only be used with {@link SVGRenderer}.
  29932. *
  29933. * @type {('round'|'bevel'|'miter')}
  29934. * @default 'round'
  29935. */
  29936. this.wireframeLinejoin = 'round';
  29937. /**
  29938. * Whether the material is rendered with flat shading or not.
  29939. *
  29940. * @type {boolean}
  29941. * @default false
  29942. */
  29943. this.flatShading = false;
  29944. /**
  29945. * Whether the material is affected by fog or not.
  29946. *
  29947. * @type {boolean}
  29948. * @default true
  29949. */
  29950. this.fog = true;
  29951. this.setValues( parameters );
  29952. }
  29953. copy( source ) {
  29954. super.copy( source );
  29955. this.color.copy( source.color );
  29956. this.map = source.map;
  29957. this.lightMap = source.lightMap;
  29958. this.lightMapIntensity = source.lightMapIntensity;
  29959. this.aoMap = source.aoMap;
  29960. this.aoMapIntensity = source.aoMapIntensity;
  29961. this.emissive.copy( source.emissive );
  29962. this.emissiveMap = source.emissiveMap;
  29963. this.emissiveIntensity = source.emissiveIntensity;
  29964. this.bumpMap = source.bumpMap;
  29965. this.bumpScale = source.bumpScale;
  29966. this.normalMap = source.normalMap;
  29967. this.normalMapType = source.normalMapType;
  29968. this.normalScale.copy( source.normalScale );
  29969. this.displacementMap = source.displacementMap;
  29970. this.displacementScale = source.displacementScale;
  29971. this.displacementBias = source.displacementBias;
  29972. this.specularMap = source.specularMap;
  29973. this.alphaMap = source.alphaMap;
  29974. this.envMap = source.envMap;
  29975. this.envMapRotation.copy( source.envMapRotation );
  29976. this.combine = source.combine;
  29977. this.reflectivity = source.reflectivity;
  29978. this.envMapIntensity = source.envMapIntensity;
  29979. this.refractionRatio = source.refractionRatio;
  29980. this.wireframe = source.wireframe;
  29981. this.wireframeLinewidth = source.wireframeLinewidth;
  29982. this.wireframeLinecap = source.wireframeLinecap;
  29983. this.wireframeLinejoin = source.wireframeLinejoin;
  29984. this.flatShading = source.flatShading;
  29985. this.fog = source.fog;
  29986. return this;
  29987. }
  29988. }
  29989. /**
  29990. * A material for drawing geometry by depth. Depth is based off of the camera
  29991. * near and far plane. White is nearest, black is farthest.
  29992. *
  29993. * @augments Material
  29994. * @demo scenes/material-browser.html#MeshDepthMaterial
  29995. */
  29996. class MeshDepthMaterial extends Material {
  29997. /**
  29998. * Constructs a new mesh depth material.
  29999. *
  30000. * @param {Object} [parameters] - An object with one or more properties
  30001. * defining the material's appearance. Any property of the material
  30002. * (including any property from inherited materials) can be passed
  30003. * in here. Color values can be passed any type of value accepted
  30004. * by {@link Color#set}.
  30005. */
  30006. constructor( parameters ) {
  30007. super();
  30008. /**
  30009. * This flag can be used for type testing.
  30010. *
  30011. * @type {boolean}
  30012. * @readonly
  30013. * @default true
  30014. */
  30015. this.isMeshDepthMaterial = true;
  30016. this.type = 'MeshDepthMaterial';
  30017. /**
  30018. * Type for depth packing.
  30019. *
  30020. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  30021. * @default BasicDepthPacking
  30022. */
  30023. this.depthPacking = BasicDepthPacking;
  30024. /**
  30025. * The color map. May optionally include an alpha channel, typically combined
  30026. * with {@link Material#transparent} or {@link Material#alphaTest}.
  30027. *
  30028. * @type {?Texture}
  30029. * @default null
  30030. */
  30031. this.map = null;
  30032. /**
  30033. * The alpha map is a grayscale texture that controls the opacity across the
  30034. * surface (black: fully transparent; white: fully opaque).
  30035. *
  30036. * Only the color of the texture is used, ignoring the alpha channel if one
  30037. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30038. * when sampling this texture due to the extra bit of precision provided for
  30039. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30040. * luminance/alpha textures will also still work as expected.
  30041. *
  30042. * @type {?Texture}
  30043. * @default null
  30044. */
  30045. this.alphaMap = null;
  30046. /**
  30047. * The displacement map affects the position of the mesh's vertices. Unlike
  30048. * other maps which only affect the light and shade of the material the
  30049. * displaced vertices can cast shadows, block other objects, and otherwise
  30050. * act as real geometry. The displacement texture is an image where the value
  30051. * of each pixel (white being the highest) is mapped against, and
  30052. * repositions, the vertices of the mesh.
  30053. *
  30054. * @type {?Texture}
  30055. * @default null
  30056. */
  30057. this.displacementMap = null;
  30058. /**
  30059. * How much the displacement map affects the mesh (where black is no
  30060. * displacement, and white is maximum displacement). Without a displacement
  30061. * map set, this value is not applied.
  30062. *
  30063. * @type {number}
  30064. * @default 0
  30065. */
  30066. this.displacementScale = 1;
  30067. /**
  30068. * The offset of the displacement map's values on the mesh's vertices.
  30069. * The bias is added to the scaled sample of the displacement map.
  30070. * Without a displacement map set, this value is not applied.
  30071. *
  30072. * @type {number}
  30073. * @default 0
  30074. */
  30075. this.displacementBias = 0;
  30076. /**
  30077. * Renders the geometry as a wireframe.
  30078. *
  30079. * @type {boolean}
  30080. * @default false
  30081. */
  30082. this.wireframe = false;
  30083. /**
  30084. * Controls the thickness of the wireframe.
  30085. *
  30086. * WebGL and WebGPU ignore this property and always render
  30087. * 1 pixel wide lines.
  30088. *
  30089. * @type {number}
  30090. * @default 1
  30091. */
  30092. this.wireframeLinewidth = 1;
  30093. this.setValues( parameters );
  30094. }
  30095. copy( source ) {
  30096. super.copy( source );
  30097. this.depthPacking = source.depthPacking;
  30098. this.map = source.map;
  30099. this.alphaMap = source.alphaMap;
  30100. this.displacementMap = source.displacementMap;
  30101. this.displacementScale = source.displacementScale;
  30102. this.displacementBias = source.displacementBias;
  30103. this.wireframe = source.wireframe;
  30104. this.wireframeLinewidth = source.wireframeLinewidth;
  30105. return this;
  30106. }
  30107. }
  30108. /**
  30109. * A material used internally for implementing shadow mapping with
  30110. * point lights.
  30111. *
  30112. * Can also be used to customize the shadow casting of an object by assigning
  30113. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  30114. * The following examples demonstrates this approach in order to ensure
  30115. * transparent parts of objects do not cast shadows.
  30116. *
  30117. * @augments Material
  30118. */
  30119. class MeshDistanceMaterial extends Material {
  30120. /**
  30121. * Constructs a new mesh distance material.
  30122. *
  30123. * @param {Object} [parameters] - An object with one or more properties
  30124. * defining the material's appearance. Any property of the material
  30125. * (including any property from inherited materials) can be passed
  30126. * in here. Color values can be passed any type of value accepted
  30127. * by {@link Color#set}.
  30128. */
  30129. constructor( parameters ) {
  30130. super();
  30131. /**
  30132. * This flag can be used for type testing.
  30133. *
  30134. * @type {boolean}
  30135. * @readonly
  30136. * @default true
  30137. */
  30138. this.isMeshDistanceMaterial = true;
  30139. this.type = 'MeshDistanceMaterial';
  30140. /**
  30141. * The color map. May optionally include an alpha channel, typically combined
  30142. * with {@link Material#transparent} or {@link Material#alphaTest}.
  30143. *
  30144. * @type {?Texture}
  30145. * @default null
  30146. */
  30147. this.map = null;
  30148. /**
  30149. * The alpha map is a grayscale texture that controls the opacity across the
  30150. * surface (black: fully transparent; white: fully opaque).
  30151. *
  30152. * Only the color of the texture is used, ignoring the alpha channel if one
  30153. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30154. * when sampling this texture due to the extra bit of precision provided for
  30155. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30156. * luminance/alpha textures will also still work as expected.
  30157. *
  30158. * @type {?Texture}
  30159. * @default null
  30160. */
  30161. this.alphaMap = null;
  30162. /**
  30163. * The displacement map affects the position of the mesh's vertices. Unlike
  30164. * other maps which only affect the light and shade of the material the
  30165. * displaced vertices can cast shadows, block other objects, and otherwise
  30166. * act as real geometry. The displacement texture is an image where the value
  30167. * of each pixel (white being the highest) is mapped against, and
  30168. * repositions, the vertices of the mesh.
  30169. *
  30170. * @type {?Texture}
  30171. * @default null
  30172. */
  30173. this.displacementMap = null;
  30174. /**
  30175. * How much the displacement map affects the mesh (where black is no
  30176. * displacement, and white is maximum displacement). Without a displacement
  30177. * map set, this value is not applied.
  30178. *
  30179. * @type {number}
  30180. * @default 0
  30181. */
  30182. this.displacementScale = 1;
  30183. /**
  30184. * The offset of the displacement map's values on the mesh's vertices.
  30185. * The bias is added to the scaled sample of the displacement map.
  30186. * Without a displacement map set, this value is not applied.
  30187. *
  30188. * @type {number}
  30189. * @default 0
  30190. */
  30191. this.displacementBias = 0;
  30192. this.setValues( parameters );
  30193. }
  30194. copy( source ) {
  30195. super.copy( source );
  30196. this.map = source.map;
  30197. this.alphaMap = source.alphaMap;
  30198. this.displacementMap = source.displacementMap;
  30199. this.displacementScale = source.displacementScale;
  30200. this.displacementBias = source.displacementBias;
  30201. return this;
  30202. }
  30203. }
  30204. /**
  30205. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  30206. * material color and shading.
  30207. *
  30208. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  30209. * baked lighting. It will cast a shadow onto an object that receives shadows
  30210. * (and shadow clipping works), but it will not self-shadow or receive
  30211. * shadows.
  30212. *
  30213. * @augments Material
  30214. * @demo scenes/material-browser.html#MeshMatcapMaterial
  30215. */
  30216. class MeshMatcapMaterial extends Material {
  30217. /**
  30218. * Constructs a new mesh matcap material.
  30219. *
  30220. * @param {Object} [parameters] - An object with one or more properties
  30221. * defining the material's appearance. Any property of the material
  30222. * (including any property from inherited materials) can be passed
  30223. * in here. Color values can be passed any type of value accepted
  30224. * by {@link Color#set}.
  30225. */
  30226. constructor( parameters ) {
  30227. super();
  30228. /**
  30229. * This flag can be used for type testing.
  30230. *
  30231. * @type {boolean}
  30232. * @readonly
  30233. * @default true
  30234. */
  30235. this.isMeshMatcapMaterial = true;
  30236. this.defines = { 'MATCAP': '' };
  30237. this.type = 'MeshMatcapMaterial';
  30238. /**
  30239. * Color of the material.
  30240. *
  30241. * @type {Color}
  30242. * @default (1,1,1)
  30243. */
  30244. this.color = new Color( 0xffffff ); // diffuse
  30245. /**
  30246. * The matcap map.
  30247. *
  30248. * @type {?Texture}
  30249. * @default null
  30250. */
  30251. this.matcap = null;
  30252. /**
  30253. * The color map. May optionally include an alpha channel, typically combined
  30254. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  30255. * color is modulated by the diffuse `color`.
  30256. *
  30257. * @type {?Texture}
  30258. * @default null
  30259. */
  30260. this.map = null;
  30261. /**
  30262. * The texture to create a bump map. The black and white values map to the
  30263. * perceived depth in relation to the lights. Bump doesn't actually affect
  30264. * the geometry of the object, only the lighting. If a normal map is defined
  30265. * this will be ignored.
  30266. *
  30267. * @type {?Texture}
  30268. * @default null
  30269. */
  30270. this.bumpMap = null;
  30271. /**
  30272. * How much the bump map affects the material. Typical range is `[0,1]`.
  30273. *
  30274. * @type {number}
  30275. * @default 1
  30276. */
  30277. this.bumpScale = 1;
  30278. /**
  30279. * The texture to create a normal map. The RGB values affect the surface
  30280. * normal for each pixel fragment and change the way the color is lit. Normal
  30281. * maps do not change the actual shape of the surface, only the lighting. In
  30282. * case the material has a normal map authored using the left handed
  30283. * convention, the `y` component of `normalScale` should be negated to compensate
  30284. * for the different handedness.
  30285. *
  30286. * @type {?Texture}
  30287. * @default null
  30288. */
  30289. this.normalMap = null;
  30290. /**
  30291. * The type of normal map.
  30292. *
  30293. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  30294. * @default TangentSpaceNormalMap
  30295. */
  30296. this.normalMapType = TangentSpaceNormalMap;
  30297. /**
  30298. * How much the normal map affects the material. Typical value range is `[0,1]`.
  30299. *
  30300. * @type {Vector2}
  30301. * @default (1,1)
  30302. */
  30303. this.normalScale = new Vector2( 1, 1 );
  30304. /**
  30305. * The displacement map affects the position of the mesh's vertices. Unlike
  30306. * other maps which only affect the light and shade of the material the
  30307. * displaced vertices can cast shadows, block other objects, and otherwise
  30308. * act as real geometry. The displacement texture is an image where the value
  30309. * of each pixel (white being the highest) is mapped against, and
  30310. * repositions, the vertices of the mesh.
  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. * @type {?Texture}
  30345. * @default null
  30346. */
  30347. this.alphaMap = null;
  30348. /**
  30349. * Renders the geometry as a wireframe.
  30350. *
  30351. * @type {boolean}
  30352. * @default false
  30353. */
  30354. this.wireframe = false;
  30355. /**
  30356. * Controls the thickness of the wireframe.
  30357. *
  30358. * Can only be used with {@link SVGRenderer}.
  30359. *
  30360. * @type {number}
  30361. * @default 1
  30362. */
  30363. this.wireframeLinewidth = 1;
  30364. /**
  30365. * Whether the material is rendered with flat shading or not.
  30366. *
  30367. * @type {boolean}
  30368. * @default false
  30369. */
  30370. this.flatShading = false;
  30371. /**
  30372. * Whether the material is affected by fog or not.
  30373. *
  30374. * @type {boolean}
  30375. * @default true
  30376. */
  30377. this.fog = true;
  30378. this.setValues( parameters );
  30379. }
  30380. copy( source ) {
  30381. super.copy( source );
  30382. this.defines = { 'MATCAP': '' };
  30383. this.color.copy( source.color );
  30384. this.matcap = source.matcap;
  30385. this.map = source.map;
  30386. this.bumpMap = source.bumpMap;
  30387. this.bumpScale = source.bumpScale;
  30388. this.normalMap = source.normalMap;
  30389. this.normalMapType = source.normalMapType;
  30390. this.normalScale.copy( source.normalScale );
  30391. this.displacementMap = source.displacementMap;
  30392. this.displacementScale = source.displacementScale;
  30393. this.displacementBias = source.displacementBias;
  30394. this.alphaMap = source.alphaMap;
  30395. this.wireframe = source.wireframe;
  30396. this.wireframeLinewidth = source.wireframeLinewidth;
  30397. this.flatShading = source.flatShading;
  30398. this.fog = source.fog;
  30399. return this;
  30400. }
  30401. }
  30402. /**
  30403. * A material for rendering line primitives.
  30404. *
  30405. * Materials define the appearance of renderable 3D objects.
  30406. *
  30407. * ```js
  30408. * const material = new THREE.LineDashedMaterial( {
  30409. * color: 0xffffff,
  30410. * scale: 1,
  30411. * dashSize: 3,
  30412. * gapSize: 1,
  30413. * } );
  30414. * ```
  30415. *
  30416. * @augments LineBasicMaterial
  30417. */
  30418. class LineDashedMaterial extends LineBasicMaterial {
  30419. /**
  30420. * Constructs a new line dashed material.
  30421. *
  30422. * @param {Object} [parameters] - An object with one or more properties
  30423. * defining the material's appearance. Any property of the material
  30424. * (including any property from inherited materials) can be passed
  30425. * in here. Color values can be passed any type of value accepted
  30426. * by {@link Color#set}.
  30427. */
  30428. constructor( parameters ) {
  30429. super();
  30430. /**
  30431. * This flag can be used for type testing.
  30432. *
  30433. * @type {boolean}
  30434. * @readonly
  30435. * @default true
  30436. */
  30437. this.isLineDashedMaterial = true;
  30438. this.type = 'LineDashedMaterial';
  30439. /**
  30440. * The scale of the dashed part of a line.
  30441. *
  30442. * @type {number}
  30443. * @default 1
  30444. */
  30445. this.scale = 1;
  30446. /**
  30447. * The size of the dash. This is both the gap with the stroke.
  30448. *
  30449. * @type {number}
  30450. * @default 3
  30451. */
  30452. this.dashSize = 3;
  30453. /**
  30454. * The size of the gap.
  30455. *
  30456. * @type {number}
  30457. * @default 1
  30458. */
  30459. this.gapSize = 1;
  30460. this.setValues( parameters );
  30461. }
  30462. copy( source ) {
  30463. super.copy( source );
  30464. this.scale = source.scale;
  30465. this.dashSize = source.dashSize;
  30466. this.gapSize = source.gapSize;
  30467. return this;
  30468. }
  30469. }
  30470. /**
  30471. * Converts an array to a specific type.
  30472. *
  30473. * @param {TypedArray|Array} array - The array to convert.
  30474. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30475. * @return {TypedArray} The converted array.
  30476. */
  30477. function convertArray( array, type ) {
  30478. if ( ! array || array.constructor === type ) return array;
  30479. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30480. return new type( array ); // create typed array
  30481. }
  30482. return Array.prototype.slice.call( array ); // create Array
  30483. }
  30484. /**
  30485. * Returns an array by which times and values can be sorted.
  30486. *
  30487. * @param {Array<number>} times - The keyframe time values.
  30488. * @return {Array<number>} The array.
  30489. */
  30490. function getKeyframeOrder( times ) {
  30491. function compareTime( i, j ) {
  30492. return times[ i ] - times[ j ];
  30493. }
  30494. const n = times.length;
  30495. const result = new Array( n );
  30496. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30497. result.sort( compareTime );
  30498. return result;
  30499. }
  30500. /**
  30501. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30502. *
  30503. * @param {Array<number>} values - The values to sort.
  30504. * @param {number} stride - The stride.
  30505. * @param {Array<number>} order - The sort order.
  30506. * @return {Array<number>} The sorted values.
  30507. */
  30508. function sortedArray( values, stride, order ) {
  30509. const nValues = values.length;
  30510. const result = new values.constructor( nValues );
  30511. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30512. const srcOffset = order[ i ] * stride;
  30513. for ( let j = 0; j !== stride; ++ j ) {
  30514. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30515. }
  30516. }
  30517. return result;
  30518. }
  30519. /**
  30520. * Used for parsing AOS keyframe formats.
  30521. *
  30522. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30523. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30524. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30525. * @param {string} valuePropertyName - The name of the property to use.
  30526. */
  30527. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30528. let i = 1, key = jsonKeys[ 0 ];
  30529. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30530. key = jsonKeys[ i ++ ];
  30531. }
  30532. if ( key === undefined ) return; // no data
  30533. let value = key[ valuePropertyName ];
  30534. if ( value === undefined ) return; // no data
  30535. if ( Array.isArray( value ) ) {
  30536. do {
  30537. value = key[ valuePropertyName ];
  30538. if ( value !== undefined ) {
  30539. times.push( key.time );
  30540. values.push( ...value ); // push all elements
  30541. }
  30542. key = jsonKeys[ i ++ ];
  30543. } while ( key !== undefined );
  30544. } else if ( value.toArray !== undefined ) {
  30545. // ...assume THREE.Math-ish
  30546. do {
  30547. value = key[ valuePropertyName ];
  30548. if ( value !== undefined ) {
  30549. times.push( key.time );
  30550. value.toArray( values, values.length );
  30551. }
  30552. key = jsonKeys[ i ++ ];
  30553. } while ( key !== undefined );
  30554. } else {
  30555. // otherwise push as-is
  30556. do {
  30557. value = key[ valuePropertyName ];
  30558. if ( value !== undefined ) {
  30559. times.push( key.time );
  30560. values.push( value );
  30561. }
  30562. key = jsonKeys[ i ++ ];
  30563. } while ( key !== undefined );
  30564. }
  30565. }
  30566. /**
  30567. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30568. *
  30569. * @param {AnimationClip} sourceClip - The values to sort.
  30570. * @param {string} name - The name of the clip.
  30571. * @param {number} startFrame - The start frame.
  30572. * @param {number} endFrame - The end frame.
  30573. * @param {number} [fps=30] - The FPS.
  30574. * @return {AnimationClip} The new sub clip.
  30575. */
  30576. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30577. const clip = sourceClip.clone();
  30578. clip.name = name;
  30579. const tracks = [];
  30580. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30581. const track = clip.tracks[ i ];
  30582. const valueSize = track.getValueSize();
  30583. const times = [];
  30584. const values = [];
  30585. for ( let j = 0; j < track.times.length; ++ j ) {
  30586. const frame = track.times[ j ] * fps;
  30587. if ( frame < startFrame || frame >= endFrame ) continue;
  30588. times.push( track.times[ j ] );
  30589. for ( let k = 0; k < valueSize; ++ k ) {
  30590. values.push( track.values[ j * valueSize + k ] );
  30591. }
  30592. }
  30593. if ( times.length === 0 ) continue;
  30594. track.times = convertArray( times, track.times.constructor );
  30595. track.values = convertArray( values, track.values.constructor );
  30596. tracks.push( track );
  30597. }
  30598. clip.tracks = tracks;
  30599. // find minimum .times value across all tracks in the trimmed clip
  30600. let minStartTime = Infinity;
  30601. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30602. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30603. minStartTime = clip.tracks[ i ].times[ 0 ];
  30604. }
  30605. }
  30606. // shift all tracks such that clip begins at t=0
  30607. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30608. clip.tracks[ i ].shift( -1 * minStartTime );
  30609. }
  30610. clip.resetDuration();
  30611. return clip;
  30612. }
  30613. /**
  30614. * Converts the keyframes of the given animation clip to an additive format.
  30615. *
  30616. * @param {AnimationClip} targetClip - The clip to make additive.
  30617. * @param {number} [referenceFrame=0] - The reference frame.
  30618. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30619. * @param {number} [fps=30] - The FPS.
  30620. * @return {AnimationClip} The updated clip which is now additive.
  30621. */
  30622. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30623. if ( fps <= 0 ) fps = 30;
  30624. const numTracks = referenceClip.tracks.length;
  30625. const referenceTime = referenceFrame / fps;
  30626. // Make each track's values relative to the values at the reference frame
  30627. for ( let i = 0; i < numTracks; ++ i ) {
  30628. const referenceTrack = referenceClip.tracks[ i ];
  30629. const referenceTrackType = referenceTrack.ValueTypeName;
  30630. // Skip this track if it's non-numeric
  30631. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30632. // Find the track in the target clip whose name and type matches the reference track
  30633. const targetTrack = targetClip.tracks.find( function ( track ) {
  30634. return track.name === referenceTrack.name
  30635. && track.ValueTypeName === referenceTrackType;
  30636. } );
  30637. if ( targetTrack === undefined ) continue;
  30638. let referenceOffset = 0;
  30639. const referenceValueSize = referenceTrack.getValueSize();
  30640. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30641. referenceOffset = referenceValueSize / 3;
  30642. }
  30643. let targetOffset = 0;
  30644. const targetValueSize = targetTrack.getValueSize();
  30645. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30646. targetOffset = targetValueSize / 3;
  30647. }
  30648. const lastIndex = referenceTrack.times.length - 1;
  30649. let referenceValue;
  30650. // Find the value to subtract out of the track
  30651. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30652. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30653. const startIndex = referenceOffset;
  30654. const endIndex = referenceValueSize - referenceOffset;
  30655. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30656. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30657. // Reference frame is after the last keyframe, so just use the last keyframe
  30658. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30659. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30660. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30661. } else {
  30662. // Interpolate to the reference value
  30663. const interpolant = referenceTrack.createInterpolant();
  30664. const startIndex = referenceOffset;
  30665. const endIndex = referenceValueSize - referenceOffset;
  30666. interpolant.evaluate( referenceTime );
  30667. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30668. }
  30669. // Conjugate the quaternion
  30670. if ( referenceTrackType === 'quaternion' ) {
  30671. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30672. referenceQuat.toArray( referenceValue );
  30673. }
  30674. // Subtract the reference value from all of the track values
  30675. const numTimes = targetTrack.times.length;
  30676. for ( let j = 0; j < numTimes; ++ j ) {
  30677. const valueStart = j * targetValueSize + targetOffset;
  30678. if ( referenceTrackType === 'quaternion' ) {
  30679. // Multiply the conjugate for quaternion track types
  30680. Quaternion.multiplyQuaternionsFlat(
  30681. targetTrack.values,
  30682. valueStart,
  30683. referenceValue,
  30684. 0,
  30685. targetTrack.values,
  30686. valueStart
  30687. );
  30688. } else {
  30689. const valueEnd = targetValueSize - targetOffset * 2;
  30690. // Subtract each value for all other numeric track types
  30691. for ( let k = 0; k < valueEnd; ++ k ) {
  30692. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30693. }
  30694. }
  30695. }
  30696. }
  30697. targetClip.blendMode = AdditiveAnimationBlendMode;
  30698. return targetClip;
  30699. }
  30700. /**
  30701. * A class with various methods to assist with animations.
  30702. *
  30703. * @hideconstructor
  30704. */
  30705. class AnimationUtils {
  30706. /**
  30707. * Converts an array to a specific type
  30708. *
  30709. * @static
  30710. * @param {TypedArray|Array} array - The array to convert.
  30711. * @param {TypedArray.constructor} type - The constructor of a type array.
  30712. * @return {TypedArray} The converted array
  30713. */
  30714. static convertArray( array, type ) {
  30715. return convertArray( array, type );
  30716. }
  30717. /**
  30718. * Returns `true` if the given object is a typed array.
  30719. *
  30720. * @static
  30721. * @param {any} object - The object to check.
  30722. * @return {boolean} Whether the given object is a typed array.
  30723. */
  30724. static isTypedArray( object ) {
  30725. return isTypedArray( object );
  30726. }
  30727. /**
  30728. * Returns an array by which times and values can be sorted.
  30729. *
  30730. * @static
  30731. * @param {Array<number>} times - The keyframe time values.
  30732. * @return {Array<number>} The array.
  30733. */
  30734. static getKeyframeOrder( times ) {
  30735. return getKeyframeOrder( times );
  30736. }
  30737. /**
  30738. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30739. *
  30740. * @static
  30741. * @param {Array<number>} values - The values to sort.
  30742. * @param {number} stride - The stride.
  30743. * @param {Array<number>} order - The sort order.
  30744. * @return {Array<number>} The sorted values.
  30745. */
  30746. static sortedArray( values, stride, order ) {
  30747. return sortedArray( values, stride, order );
  30748. }
  30749. /**
  30750. * Used for parsing AOS keyframe formats.
  30751. *
  30752. * @static
  30753. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30754. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30755. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30756. * @param {string} valuePropertyName - The name of the property to use.
  30757. */
  30758. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30759. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30760. }
  30761. /**
  30762. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30763. *
  30764. * @static
  30765. * @param {AnimationClip} sourceClip - The values to sort.
  30766. * @param {string} name - The name of the clip.
  30767. * @param {number} startFrame - The start frame.
  30768. * @param {number} endFrame - The end frame.
  30769. * @param {number} [fps=30] - The FPS.
  30770. * @return {AnimationClip} The new sub clip.
  30771. */
  30772. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30773. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30774. }
  30775. /**
  30776. * Converts the keyframes of the given animation clip to an additive format.
  30777. *
  30778. * @static
  30779. * @param {AnimationClip} targetClip - The clip to make additive.
  30780. * @param {number} [referenceFrame=0] - The reference frame.
  30781. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30782. * @param {number} [fps=30] - The FPS.
  30783. * @return {AnimationClip} The updated clip which is now additive.
  30784. */
  30785. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30786. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30787. }
  30788. }
  30789. /**
  30790. * Abstract base class of interpolants over parametric samples.
  30791. *
  30792. * The parameter domain is one dimensional, typically the time or a path
  30793. * along a curve defined by the data.
  30794. *
  30795. * The sample values can have any dimensionality and derived classes may
  30796. * apply special interpretations to the data.
  30797. *
  30798. * This class provides the interval seek in a Template Method, deferring
  30799. * the actual interpolation to derived classes.
  30800. *
  30801. * Time complexity is O(1) for linear access crossing at most two points
  30802. * and O(log N) for random access, where N is the number of positions.
  30803. *
  30804. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30805. *
  30806. * @abstract
  30807. */
  30808. class Interpolant {
  30809. /**
  30810. * Constructs a new interpolant.
  30811. *
  30812. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30813. * @param {TypedArray} sampleValues - The sample values.
  30814. * @param {number} sampleSize - The sample size
  30815. * @param {TypedArray} [resultBuffer] - The result buffer.
  30816. */
  30817. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30818. /**
  30819. * The parameter positions.
  30820. *
  30821. * @type {TypedArray}
  30822. */
  30823. this.parameterPositions = parameterPositions;
  30824. /**
  30825. * A cache index.
  30826. *
  30827. * @private
  30828. * @type {number}
  30829. * @default 0
  30830. */
  30831. this._cachedIndex = 0;
  30832. /**
  30833. * The result buffer.
  30834. *
  30835. * @type {TypedArray}
  30836. */
  30837. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30838. /**
  30839. * The sample values.
  30840. *
  30841. * @type {TypedArray}
  30842. */
  30843. this.sampleValues = sampleValues;
  30844. /**
  30845. * The value size.
  30846. *
  30847. * @type {TypedArray}
  30848. */
  30849. this.valueSize = sampleSize;
  30850. /**
  30851. * The interpolation settings.
  30852. *
  30853. * @type {?Object}
  30854. * @default null
  30855. */
  30856. this.settings = null;
  30857. /**
  30858. * The default settings object.
  30859. *
  30860. * @type {Object}
  30861. */
  30862. this.DefaultSettings_ = {};
  30863. }
  30864. /**
  30865. * Evaluate the interpolant at position `t`.
  30866. *
  30867. * @param {number} t - The interpolation factor.
  30868. * @return {TypedArray} The result buffer.
  30869. */
  30870. evaluate( t ) {
  30871. const pp = this.parameterPositions;
  30872. let i1 = this._cachedIndex,
  30873. t1 = pp[ i1 ],
  30874. t0 = pp[ i1 - 1 ];
  30875. validate_interval: {
  30876. seek: {
  30877. let right;
  30878. linear_scan: {
  30879. //- See http://jsperf.com/comparison-to-undefined/3
  30880. //- slower code:
  30881. //-
  30882. //- if ( t >= t1 || t1 === undefined ) {
  30883. forward_scan: if ( ! ( t < t1 ) ) {
  30884. for ( let giveUpAt = i1 + 2; ; ) {
  30885. if ( t1 === undefined ) {
  30886. if ( t < t0 ) break forward_scan;
  30887. // after end
  30888. i1 = pp.length;
  30889. this._cachedIndex = i1;
  30890. return this.copySampleValue_( i1 - 1 );
  30891. }
  30892. if ( i1 === giveUpAt ) break; // this loop
  30893. t0 = t1;
  30894. t1 = pp[ ++ i1 ];
  30895. if ( t < t1 ) {
  30896. // we have arrived at the sought interval
  30897. break seek;
  30898. }
  30899. }
  30900. // prepare binary search on the right side of the index
  30901. right = pp.length;
  30902. break linear_scan;
  30903. }
  30904. //- slower code:
  30905. //- if ( t < t0 || t0 === undefined ) {
  30906. if ( ! ( t >= t0 ) ) {
  30907. // looping?
  30908. const t1global = pp[ 1 ];
  30909. if ( t < t1global ) {
  30910. i1 = 2; // + 1, using the scan for the details
  30911. t0 = t1global;
  30912. }
  30913. // linear reverse scan
  30914. for ( let giveUpAt = i1 - 2; ; ) {
  30915. if ( t0 === undefined ) {
  30916. // before start
  30917. this._cachedIndex = 0;
  30918. return this.copySampleValue_( 0 );
  30919. }
  30920. if ( i1 === giveUpAt ) break; // this loop
  30921. t1 = t0;
  30922. t0 = pp[ -- i1 - 1 ];
  30923. if ( t >= t0 ) {
  30924. // we have arrived at the sought interval
  30925. break seek;
  30926. }
  30927. }
  30928. // prepare binary search on the left side of the index
  30929. right = i1;
  30930. i1 = 0;
  30931. break linear_scan;
  30932. }
  30933. // the interval is valid
  30934. break validate_interval;
  30935. } // linear scan
  30936. // binary search
  30937. while ( i1 < right ) {
  30938. const mid = ( i1 + right ) >>> 1;
  30939. if ( t < pp[ mid ] ) {
  30940. right = mid;
  30941. } else {
  30942. i1 = mid + 1;
  30943. }
  30944. }
  30945. t1 = pp[ i1 ];
  30946. t0 = pp[ i1 - 1 ];
  30947. // check boundary cases, again
  30948. if ( t0 === undefined ) {
  30949. this._cachedIndex = 0;
  30950. return this.copySampleValue_( 0 );
  30951. }
  30952. if ( t1 === undefined ) {
  30953. i1 = pp.length;
  30954. this._cachedIndex = i1;
  30955. return this.copySampleValue_( i1 - 1 );
  30956. }
  30957. } // seek
  30958. this._cachedIndex = i1;
  30959. this.intervalChanged_( i1, t0, t1 );
  30960. } // validate_interval
  30961. return this.interpolate_( i1, t0, t, t1 );
  30962. }
  30963. /**
  30964. * Returns the interpolation settings.
  30965. *
  30966. * @return {Object} The interpolation settings.
  30967. */
  30968. getSettings_() {
  30969. return this.settings || this.DefaultSettings_;
  30970. }
  30971. /**
  30972. * Copies a sample value to the result buffer.
  30973. *
  30974. * @param {number} index - An index into the sample value buffer.
  30975. * @return {TypedArray} The result buffer.
  30976. */
  30977. copySampleValue_( index ) {
  30978. // copies a sample value to the result buffer
  30979. const result = this.resultBuffer,
  30980. values = this.sampleValues,
  30981. stride = this.valueSize,
  30982. offset = index * stride;
  30983. for ( let i = 0; i !== stride; ++ i ) {
  30984. result[ i ] = values[ offset + i ];
  30985. }
  30986. return result;
  30987. }
  30988. /**
  30989. * Copies a sample value to the result buffer.
  30990. *
  30991. * @abstract
  30992. * @param {number} i1 - An index into the sample value buffer.
  30993. * @param {number} t0 - The previous interpolation factor.
  30994. * @param {number} t - The current interpolation factor.
  30995. * @param {number} t1 - The next interpolation factor.
  30996. * @return {TypedArray} The result buffer.
  30997. */
  30998. interpolate_( /* i1, t0, t, t1 */ ) {
  30999. throw new Error( 'call to abstract method' );
  31000. // implementations shall return this.resultBuffer
  31001. }
  31002. /**
  31003. * Optional method that is executed when the interval has changed.
  31004. *
  31005. * @param {number} i1 - An index into the sample value buffer.
  31006. * @param {number} t0 - The previous interpolation factor.
  31007. * @param {number} t - The current interpolation factor.
  31008. */
  31009. intervalChanged_( /* i1, t0, t1 */ ) {
  31010. // empty
  31011. }
  31012. }
  31013. /**
  31014. * Fast and simple cubic spline interpolant.
  31015. *
  31016. * It was derived from a Hermitian construction setting the first derivative
  31017. * at each sample position to the linear slope between neighboring positions
  31018. * over their parameter interval.
  31019. *
  31020. * @augments Interpolant
  31021. */
  31022. class CubicInterpolant extends Interpolant {
  31023. /**
  31024. * Constructs a new cubic interpolant.
  31025. *
  31026. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31027. * @param {TypedArray} sampleValues - The sample values.
  31028. * @param {number} sampleSize - The sample size
  31029. * @param {TypedArray} [resultBuffer] - The result buffer.
  31030. */
  31031. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31032. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31033. this._weightPrev = -0;
  31034. this._offsetPrev = -0;
  31035. this._weightNext = -0;
  31036. this._offsetNext = -0;
  31037. this.DefaultSettings_ = {
  31038. endingStart: ZeroCurvatureEnding,
  31039. endingEnd: ZeroCurvatureEnding
  31040. };
  31041. }
  31042. intervalChanged_( i1, t0, t1 ) {
  31043. const pp = this.parameterPositions;
  31044. let iPrev = i1 - 2,
  31045. iNext = i1 + 1,
  31046. tPrev = pp[ iPrev ],
  31047. tNext = pp[ iNext ];
  31048. if ( tPrev === undefined ) {
  31049. switch ( this.getSettings_().endingStart ) {
  31050. case ZeroSlopeEnding:
  31051. // f'(t0) = 0
  31052. iPrev = i1;
  31053. tPrev = 2 * t0 - t1;
  31054. break;
  31055. case WrapAroundEnding:
  31056. // use the other end of the curve
  31057. iPrev = pp.length - 2;
  31058. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  31059. break;
  31060. default: // ZeroCurvatureEnding
  31061. // f''(t0) = 0 a.k.a. Natural Spline
  31062. iPrev = i1;
  31063. tPrev = t1;
  31064. }
  31065. }
  31066. if ( tNext === undefined ) {
  31067. switch ( this.getSettings_().endingEnd ) {
  31068. case ZeroSlopeEnding:
  31069. // f'(tN) = 0
  31070. iNext = i1;
  31071. tNext = 2 * t1 - t0;
  31072. break;
  31073. case WrapAroundEnding:
  31074. // use the other end of the curve
  31075. iNext = 1;
  31076. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  31077. break;
  31078. default: // ZeroCurvatureEnding
  31079. // f''(tN) = 0, a.k.a. Natural Spline
  31080. iNext = i1 - 1;
  31081. tNext = t0;
  31082. }
  31083. }
  31084. const halfDt = ( t1 - t0 ) * 0.5,
  31085. stride = this.valueSize;
  31086. this._weightPrev = halfDt / ( t0 - tPrev );
  31087. this._weightNext = halfDt / ( tNext - t1 );
  31088. this._offsetPrev = iPrev * stride;
  31089. this._offsetNext = iNext * stride;
  31090. }
  31091. interpolate_( i1, t0, t, t1 ) {
  31092. const result = this.resultBuffer,
  31093. values = this.sampleValues,
  31094. stride = this.valueSize,
  31095. o1 = i1 * stride, o0 = o1 - stride,
  31096. oP = this._offsetPrev, oN = this._offsetNext,
  31097. wP = this._weightPrev, wN = this._weightNext,
  31098. p = ( t - t0 ) / ( t1 - t0 ),
  31099. pp = p * p,
  31100. ppp = pp * p;
  31101. // evaluate polynomials
  31102. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  31103. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  31104. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  31105. const sN = wN * ppp - wN * pp;
  31106. // combine data linearly
  31107. for ( let i = 0; i !== stride; ++ i ) {
  31108. result[ i ] =
  31109. sP * values[ oP + i ] +
  31110. s0 * values[ o0 + i ] +
  31111. s1 * values[ o1 + i ] +
  31112. sN * values[ oN + i ];
  31113. }
  31114. return result;
  31115. }
  31116. }
  31117. /**
  31118. * A basic linear interpolant.
  31119. *
  31120. * @augments Interpolant
  31121. */
  31122. class LinearInterpolant extends Interpolant {
  31123. /**
  31124. * Constructs a new linear interpolant.
  31125. *
  31126. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31127. * @param {TypedArray} sampleValues - The sample values.
  31128. * @param {number} sampleSize - The sample size
  31129. * @param {TypedArray} [resultBuffer] - The result buffer.
  31130. */
  31131. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31132. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31133. }
  31134. interpolate_( i1, t0, t, t1 ) {
  31135. const result = this.resultBuffer,
  31136. values = this.sampleValues,
  31137. stride = this.valueSize,
  31138. offset1 = i1 * stride,
  31139. offset0 = offset1 - stride,
  31140. weight1 = ( t - t0 ) / ( t1 - t0 ),
  31141. weight0 = 1 - weight1;
  31142. for ( let i = 0; i !== stride; ++ i ) {
  31143. result[ i ] =
  31144. values[ offset0 + i ] * weight0 +
  31145. values[ offset1 + i ] * weight1;
  31146. }
  31147. return result;
  31148. }
  31149. }
  31150. /**
  31151. * Interpolant that evaluates to the sample value at the position preceding
  31152. * the parameter.
  31153. *
  31154. * @augments Interpolant
  31155. */
  31156. class DiscreteInterpolant extends Interpolant {
  31157. /**
  31158. * Constructs a new discrete interpolant.
  31159. *
  31160. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31161. * @param {TypedArray} sampleValues - The sample values.
  31162. * @param {number} sampleSize - The sample size
  31163. * @param {TypedArray} [resultBuffer] - The result buffer.
  31164. */
  31165. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31166. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31167. }
  31168. interpolate_( i1 /*, t0, t, t1 */ ) {
  31169. return this.copySampleValue_( i1 - 1 );
  31170. }
  31171. }
  31172. /**
  31173. * A Bezier interpolant using cubic Bezier curves with 2D control points.
  31174. *
  31175. * This interpolant supports the COLLADA/Maya style of Bezier animation where
  31176. * each keyframe has explicit in/out tangent control points specified as
  31177. * 2D coordinates (time, value).
  31178. *
  31179. * The tangent data must be provided via the `settings` object:
  31180. * - `settings.inTangents`: Float32Array with [time, value] pairs per keyframe per component
  31181. * - `settings.outTangents`: Float32Array with [time, value] pairs per keyframe per component
  31182. *
  31183. * For a track with N keyframes and stride S:
  31184. * - Each tangent array has N * S * 2 values
  31185. * - Layout: [k0_c0_time, k0_c0_value, k0_c1_time, k0_c1_value, ..., k0_cS_time, k0_cS_value,
  31186. * k1_c0_time, k1_c0_value, ...]
  31187. *
  31188. * @augments Interpolant
  31189. */
  31190. class BezierInterpolant extends Interpolant {
  31191. interpolate_( i1, t0, t, t1 ) {
  31192. const result = this.resultBuffer;
  31193. const values = this.sampleValues;
  31194. const stride = this.valueSize;
  31195. const offset1 = i1 * stride;
  31196. const offset0 = offset1 - stride;
  31197. const settings = this.settings || this.DefaultSettings_;
  31198. const inTangents = settings.inTangents;
  31199. const outTangents = settings.outTangents;
  31200. // If no tangent data, fall back to linear interpolation
  31201. if ( ! inTangents || ! outTangents ) {
  31202. const weight1 = ( t - t0 ) / ( t1 - t0 );
  31203. const weight0 = 1 - weight1;
  31204. for ( let i = 0; i !== stride; ++ i ) {
  31205. result[ i ] = values[ offset0 + i ] * weight0 + values[ offset1 + i ] * weight1;
  31206. }
  31207. return result;
  31208. }
  31209. const tangentStride = stride * 2;
  31210. const i0 = i1 - 1;
  31211. for ( let i = 0; i !== stride; ++ i ) {
  31212. const v0 = values[ offset0 + i ];
  31213. const v1 = values[ offset1 + i ];
  31214. // outTangent of previous keyframe (C0)
  31215. const outTangentOffset = i0 * tangentStride + i * 2;
  31216. const c0x = outTangents[ outTangentOffset ];
  31217. const c0y = outTangents[ outTangentOffset + 1 ];
  31218. // inTangent of current keyframe (C1)
  31219. const inTangentOffset = i1 * tangentStride + i * 2;
  31220. const c1x = inTangents[ inTangentOffset ];
  31221. const c1y = inTangents[ inTangentOffset + 1 ];
  31222. // Solve for Bezier parameter s where Bx(s) = t using Newton-Raphson
  31223. let s = ( t - t0 ) / ( t1 - t0 );
  31224. let s2, s3, oneMinusS, oneMinusS2, oneMinusS3;
  31225. for ( let iter = 0; iter < 8; iter ++ ) {
  31226. s2 = s * s;
  31227. s3 = s2 * s;
  31228. oneMinusS = 1 - s;
  31229. oneMinusS2 = oneMinusS * oneMinusS;
  31230. oneMinusS3 = oneMinusS2 * oneMinusS;
  31231. // Bezier X(s) = (1-s)³·t0 + 3(1-s)²s·c0x + 3(1-s)s²·c1x + s³·t1
  31232. const bx = oneMinusS3 * t0 + 3 * oneMinusS2 * s * c0x + 3 * oneMinusS * s2 * c1x + s3 * t1;
  31233. const error = bx - t;
  31234. if ( Math.abs( error ) < 1e-10 ) break;
  31235. // Derivative dX/ds
  31236. const dbx = 3 * oneMinusS2 * ( c0x - t0 ) + 6 * oneMinusS * s * ( c1x - c0x ) + 3 * s2 * ( t1 - c1x );
  31237. if ( Math.abs( dbx ) < 1e-10 ) break;
  31238. s = s - error / dbx;
  31239. s = Math.max( 0, Math.min( 1, s ) );
  31240. }
  31241. // Evaluate Bezier Y(s)
  31242. result[ i ] = oneMinusS3 * v0 + 3 * oneMinusS2 * s * c0y + 3 * oneMinusS * s2 * c1y + s3 * v1;
  31243. }
  31244. return result;
  31245. }
  31246. }
  31247. /**
  31248. * Represents a timed sequence of keyframes, which are composed of lists of
  31249. * times and related values, and which are used to animate a specific property
  31250. * of an object.
  31251. */
  31252. class KeyframeTrack {
  31253. /**
  31254. * Constructs a new keyframe track.
  31255. *
  31256. * @param {string} name - The keyframe track's name.
  31257. * @param {Array<number>} times - A list of keyframe times.
  31258. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  31259. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} [interpolation] - The interpolation type.
  31260. */
  31261. constructor( name, times, values, interpolation ) {
  31262. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  31263. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  31264. /**
  31265. * The track's name can refer to morph targets or bones or
  31266. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  31267. * for the forms of strings that can be parsed for property binding.
  31268. *
  31269. * @type {string}
  31270. */
  31271. this.name = name;
  31272. /**
  31273. * The keyframe times.
  31274. *
  31275. * @type {Float32Array}
  31276. */
  31277. this.times = convertArray( times, this.TimeBufferType );
  31278. /**
  31279. * The keyframe values.
  31280. *
  31281. * @type {Float32Array}
  31282. */
  31283. this.values = convertArray( values, this.ValueBufferType );
  31284. this.setInterpolation( interpolation || this.DefaultInterpolation );
  31285. }
  31286. /**
  31287. * Converts the keyframe track to JSON.
  31288. *
  31289. * @static
  31290. * @param {KeyframeTrack} track - The keyframe track to serialize.
  31291. * @return {Object} The serialized keyframe track as JSON.
  31292. */
  31293. static toJSON( track ) {
  31294. const trackType = track.constructor;
  31295. let json;
  31296. // derived classes can define a static toJSON method
  31297. if ( trackType.toJSON !== this.toJSON ) {
  31298. json = trackType.toJSON( track );
  31299. } else {
  31300. // by default, we assume the data can be serialized as-is
  31301. json = {
  31302. 'name': track.name,
  31303. 'times': convertArray( track.times, Array ),
  31304. 'values': convertArray( track.values, Array )
  31305. };
  31306. const interpolation = track.getInterpolation();
  31307. if ( interpolation !== track.DefaultInterpolation ) {
  31308. json.interpolation = interpolation;
  31309. }
  31310. }
  31311. json.type = track.ValueTypeName; // mandatory
  31312. return json;
  31313. }
  31314. /**
  31315. * Factory method for creating a new discrete interpolant.
  31316. *
  31317. * @static
  31318. * @param {TypedArray} [result] - The result buffer.
  31319. * @return {DiscreteInterpolant} The new interpolant.
  31320. */
  31321. InterpolantFactoryMethodDiscrete( result ) {
  31322. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  31323. }
  31324. /**
  31325. * Factory method for creating a new linear interpolant.
  31326. *
  31327. * @static
  31328. * @param {TypedArray} [result] - The result buffer.
  31329. * @return {LinearInterpolant} The new interpolant.
  31330. */
  31331. InterpolantFactoryMethodLinear( result ) {
  31332. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31333. }
  31334. /**
  31335. * Factory method for creating a new smooth interpolant.
  31336. *
  31337. * @static
  31338. * @param {TypedArray} [result] - The result buffer.
  31339. * @return {CubicInterpolant} The new interpolant.
  31340. */
  31341. InterpolantFactoryMethodSmooth( result ) {
  31342. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  31343. }
  31344. /**
  31345. * Factory method for creating a new Bezier interpolant.
  31346. *
  31347. * The Bezier interpolant requires tangent data to be set via the `settings` property
  31348. * on the track before creating the interpolant. The settings should contain:
  31349. * - `inTangents`: Float32Array with [time, value] pairs per keyframe per component
  31350. * - `outTangents`: Float32Array with [time, value] pairs per keyframe per component
  31351. *
  31352. * @static
  31353. * @param {TypedArray} [result] - The result buffer.
  31354. * @return {BezierInterpolant} The new interpolant.
  31355. */
  31356. InterpolantFactoryMethodBezier( result ) {
  31357. const interpolant = new BezierInterpolant( this.times, this.values, this.getValueSize(), result );
  31358. // Pass tangent data from track settings to interpolant
  31359. if ( this.settings ) {
  31360. interpolant.settings = this.settings;
  31361. }
  31362. return interpolant;
  31363. }
  31364. /**
  31365. * Defines the interpolation factor method for this keyframe track.
  31366. *
  31367. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} interpolation - The interpolation type.
  31368. * @return {KeyframeTrack} A reference to this keyframe track.
  31369. */
  31370. setInterpolation( interpolation ) {
  31371. let factoryMethod;
  31372. switch ( interpolation ) {
  31373. case InterpolateDiscrete:
  31374. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  31375. break;
  31376. case InterpolateLinear:
  31377. factoryMethod = this.InterpolantFactoryMethodLinear;
  31378. break;
  31379. case InterpolateSmooth:
  31380. factoryMethod = this.InterpolantFactoryMethodSmooth;
  31381. break;
  31382. case InterpolateBezier:
  31383. factoryMethod = this.InterpolantFactoryMethodBezier;
  31384. break;
  31385. }
  31386. if ( factoryMethod === undefined ) {
  31387. const message = 'unsupported interpolation for ' +
  31388. this.ValueTypeName + ' keyframe track named ' + this.name;
  31389. if ( this.createInterpolant === undefined ) {
  31390. // fall back to default, unless the default itself is messed up
  31391. if ( interpolation !== this.DefaultInterpolation ) {
  31392. this.setInterpolation( this.DefaultInterpolation );
  31393. } else {
  31394. throw new Error( message ); // fatal, in this case
  31395. }
  31396. }
  31397. warn( 'KeyframeTrack:', message );
  31398. return this;
  31399. }
  31400. this.createInterpolant = factoryMethod;
  31401. return this;
  31402. }
  31403. /**
  31404. * Returns the current interpolation type.
  31405. *
  31406. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} The interpolation type.
  31407. */
  31408. getInterpolation() {
  31409. switch ( this.createInterpolant ) {
  31410. case this.InterpolantFactoryMethodDiscrete:
  31411. return InterpolateDiscrete;
  31412. case this.InterpolantFactoryMethodLinear:
  31413. return InterpolateLinear;
  31414. case this.InterpolantFactoryMethodSmooth:
  31415. return InterpolateSmooth;
  31416. case this.InterpolantFactoryMethodBezier:
  31417. return InterpolateBezier;
  31418. }
  31419. }
  31420. /**
  31421. * Returns the value size.
  31422. *
  31423. * @return {number} The value size.
  31424. */
  31425. getValueSize() {
  31426. return this.values.length / this.times.length;
  31427. }
  31428. /**
  31429. * Moves all keyframes either forward or backward in time.
  31430. *
  31431. * @param {number} timeOffset - The offset to move the time values.
  31432. * @return {KeyframeTrack} A reference to this keyframe track.
  31433. */
  31434. shift( timeOffset ) {
  31435. if ( timeOffset !== 0.0 ) {
  31436. const times = this.times;
  31437. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31438. times[ i ] += timeOffset;
  31439. }
  31440. }
  31441. return this;
  31442. }
  31443. /**
  31444. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  31445. *
  31446. * @param {number} timeScale - The time scale.
  31447. * @return {KeyframeTrack} A reference to this keyframe track.
  31448. */
  31449. scale( timeScale ) {
  31450. if ( timeScale !== 1.0 ) {
  31451. const times = this.times;
  31452. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31453. times[ i ] *= timeScale;
  31454. }
  31455. }
  31456. return this;
  31457. }
  31458. /**
  31459. * Removes keyframes before and after animation without changing any values within the defined time range.
  31460. *
  31461. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  31462. * keys this will change their values
  31463. *
  31464. * @param {number} startTime - The start time.
  31465. * @param {number} endTime - The end time.
  31466. * @return {KeyframeTrack} A reference to this keyframe track.
  31467. */
  31468. trim( startTime, endTime ) {
  31469. const times = this.times,
  31470. nKeys = times.length;
  31471. let from = 0,
  31472. to = nKeys - 1;
  31473. while ( from !== nKeys && times[ from ] < startTime ) {
  31474. ++ from;
  31475. }
  31476. while ( to !== -1 && times[ to ] > endTime ) {
  31477. -- to;
  31478. }
  31479. ++ to; // inclusive -> exclusive bound
  31480. if ( from !== 0 || to !== nKeys ) {
  31481. // empty tracks are forbidden, so keep at least one keyframe
  31482. if ( from >= to ) {
  31483. to = Math.max( to, 1 );
  31484. from = to - 1;
  31485. }
  31486. const stride = this.getValueSize();
  31487. this.times = times.slice( from, to );
  31488. this.values = this.values.slice( from * stride, to * stride );
  31489. }
  31490. return this;
  31491. }
  31492. /**
  31493. * Performs minimal validation on the keyframe track. Returns `true` if the values
  31494. * are valid.
  31495. *
  31496. * @return {boolean} Whether the keyframes are valid or not.
  31497. */
  31498. validate() {
  31499. let valid = true;
  31500. const valueSize = this.getValueSize();
  31501. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  31502. error( 'KeyframeTrack: Invalid value size in track.', this );
  31503. valid = false;
  31504. }
  31505. const times = this.times,
  31506. values = this.values,
  31507. nKeys = times.length;
  31508. if ( nKeys === 0 ) {
  31509. error( 'KeyframeTrack: Track is empty.', this );
  31510. valid = false;
  31511. }
  31512. let prevTime = null;
  31513. for ( let i = 0; i !== nKeys; i ++ ) {
  31514. const currTime = times[ i ];
  31515. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31516. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31517. valid = false;
  31518. break;
  31519. }
  31520. if ( prevTime !== null && prevTime > currTime ) {
  31521. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31522. valid = false;
  31523. break;
  31524. }
  31525. prevTime = currTime;
  31526. }
  31527. if ( values !== undefined ) {
  31528. if ( isTypedArray( values ) ) {
  31529. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31530. const value = values[ i ];
  31531. if ( isNaN( value ) ) {
  31532. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31533. valid = false;
  31534. break;
  31535. }
  31536. }
  31537. }
  31538. }
  31539. return valid;
  31540. }
  31541. /**
  31542. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31543. * common in morph target sequences).
  31544. *
  31545. * @return {KeyframeTrack} A reference to this keyframe track.
  31546. */
  31547. optimize() {
  31548. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31549. // times or values may be shared with other tracks, so overwriting is unsafe
  31550. const times = this.times.slice(),
  31551. values = this.values.slice(),
  31552. stride = this.getValueSize(),
  31553. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31554. lastIndex = times.length - 1;
  31555. let writeIndex = 1;
  31556. for ( let i = 1; i < lastIndex; ++ i ) {
  31557. let keep = false;
  31558. const time = times[ i ];
  31559. const timeNext = times[ i + 1 ];
  31560. // remove adjacent keyframes scheduled at the same time
  31561. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31562. if ( ! smoothInterpolation ) {
  31563. // remove unnecessary keyframes same as their neighbors
  31564. const offset = i * stride,
  31565. offsetP = offset - stride,
  31566. offsetN = offset + stride;
  31567. for ( let j = 0; j !== stride; ++ j ) {
  31568. const value = values[ offset + j ];
  31569. if ( value !== values[ offsetP + j ] ||
  31570. value !== values[ offsetN + j ] ) {
  31571. keep = true;
  31572. break;
  31573. }
  31574. }
  31575. } else {
  31576. keep = true;
  31577. }
  31578. }
  31579. // in-place compaction
  31580. if ( keep ) {
  31581. if ( i !== writeIndex ) {
  31582. times[ writeIndex ] = times[ i ];
  31583. const readOffset = i * stride,
  31584. writeOffset = writeIndex * stride;
  31585. for ( let j = 0; j !== stride; ++ j ) {
  31586. values[ writeOffset + j ] = values[ readOffset + j ];
  31587. }
  31588. }
  31589. ++ writeIndex;
  31590. }
  31591. }
  31592. // flush last keyframe (compaction looks ahead)
  31593. if ( lastIndex > 0 ) {
  31594. times[ writeIndex ] = times[ lastIndex ];
  31595. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31596. values[ writeOffset + j ] = values[ readOffset + j ];
  31597. }
  31598. ++ writeIndex;
  31599. }
  31600. if ( writeIndex !== times.length ) {
  31601. this.times = times.slice( 0, writeIndex );
  31602. this.values = values.slice( 0, writeIndex * stride );
  31603. } else {
  31604. this.times = times;
  31605. this.values = values;
  31606. }
  31607. return this;
  31608. }
  31609. /**
  31610. * Returns a new keyframe track with copied values from this instance.
  31611. *
  31612. * @return {KeyframeTrack} A clone of this instance.
  31613. */
  31614. clone() {
  31615. const times = this.times.slice();
  31616. const values = this.values.slice();
  31617. const TypedKeyframeTrack = this.constructor;
  31618. const track = new TypedKeyframeTrack( this.name, times, values );
  31619. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31620. track.createInterpolant = this.createInterpolant;
  31621. return track;
  31622. }
  31623. }
  31624. /**
  31625. * The value type name.
  31626. *
  31627. * @type {string}
  31628. * @default ''
  31629. */
  31630. KeyframeTrack.prototype.ValueTypeName = '';
  31631. /**
  31632. * The time buffer type of this keyframe track.
  31633. *
  31634. * @type {TypedArray|Array}
  31635. * @default Float32Array.constructor
  31636. */
  31637. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31638. /**
  31639. * The value buffer type of this keyframe track.
  31640. *
  31641. * @type {TypedArray|Array}
  31642. * @default Float32Array.constructor
  31643. */
  31644. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31645. /**
  31646. * The default interpolation type of this keyframe track.
  31647. *
  31648. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)}
  31649. * @default InterpolateLinear
  31650. */
  31651. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31652. /**
  31653. * A track for boolean keyframe values.
  31654. *
  31655. * @augments KeyframeTrack
  31656. */
  31657. class BooleanKeyframeTrack extends KeyframeTrack {
  31658. /**
  31659. * Constructs a new boolean keyframe track.
  31660. *
  31661. * This keyframe track type has no `interpolation` parameter because the
  31662. * interpolation is always discrete.
  31663. *
  31664. * @param {string} name - The keyframe track's name.
  31665. * @param {Array<number>} times - A list of keyframe times.
  31666. * @param {Array<boolean>} values - A list of keyframe values.
  31667. */
  31668. constructor( name, times, values ) {
  31669. super( name, times, values );
  31670. }
  31671. }
  31672. /**
  31673. * The value type name.
  31674. *
  31675. * @type {string}
  31676. * @default 'bool'
  31677. */
  31678. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31679. /**
  31680. * The value buffer type of this keyframe track.
  31681. *
  31682. * @type {TypedArray|Array}
  31683. * @default Array.constructor
  31684. */
  31685. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31686. /**
  31687. * The default interpolation type of this keyframe track.
  31688. *
  31689. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31690. * @default InterpolateDiscrete
  31691. */
  31692. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31693. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31694. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31695. /**
  31696. * A track for color keyframe values.
  31697. *
  31698. * @augments KeyframeTrack
  31699. */
  31700. class ColorKeyframeTrack extends KeyframeTrack {
  31701. /**
  31702. * Constructs a new color keyframe track.
  31703. *
  31704. * @param {string} name - The keyframe track's name.
  31705. * @param {Array<number>} times - A list of keyframe times.
  31706. * @param {Array<number>} values - A list of keyframe values.
  31707. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31708. */
  31709. constructor( name, times, values, interpolation ) {
  31710. super( name, times, values, interpolation );
  31711. }
  31712. }
  31713. /**
  31714. * The value type name.
  31715. *
  31716. * @type {string}
  31717. * @default 'color'
  31718. */
  31719. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31720. /**
  31721. * A track for numeric keyframe values.
  31722. *
  31723. * @augments KeyframeTrack
  31724. */
  31725. class NumberKeyframeTrack extends KeyframeTrack {
  31726. /**
  31727. * Constructs a new number keyframe track.
  31728. *
  31729. * @param {string} name - The keyframe track's name.
  31730. * @param {Array<number>} times - A list of keyframe times.
  31731. * @param {Array<number>} values - A list of keyframe values.
  31732. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31733. */
  31734. constructor( name, times, values, interpolation ) {
  31735. super( name, times, values, interpolation );
  31736. }
  31737. }
  31738. /**
  31739. * The value type name.
  31740. *
  31741. * @type {string}
  31742. * @default 'number'
  31743. */
  31744. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31745. /**
  31746. * Spherical linear unit quaternion interpolant.
  31747. *
  31748. * @augments Interpolant
  31749. */
  31750. class QuaternionLinearInterpolant extends Interpolant {
  31751. /**
  31752. * Constructs a new SLERP interpolant.
  31753. *
  31754. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31755. * @param {TypedArray} sampleValues - The sample values.
  31756. * @param {number} sampleSize - The sample size
  31757. * @param {TypedArray} [resultBuffer] - The result buffer.
  31758. */
  31759. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31760. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31761. }
  31762. interpolate_( i1, t0, t, t1 ) {
  31763. const result = this.resultBuffer,
  31764. values = this.sampleValues,
  31765. stride = this.valueSize,
  31766. alpha = ( t - t0 ) / ( t1 - t0 );
  31767. let offset = i1 * stride;
  31768. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31769. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31770. }
  31771. return result;
  31772. }
  31773. }
  31774. /**
  31775. * A track for Quaternion keyframe values.
  31776. *
  31777. * @augments KeyframeTrack
  31778. */
  31779. class QuaternionKeyframeTrack extends KeyframeTrack {
  31780. /**
  31781. * Constructs a new Quaternion keyframe track.
  31782. *
  31783. * @param {string} name - The keyframe track's name.
  31784. * @param {Array<number>} times - A list of keyframe times.
  31785. * @param {Array<number>} values - A list of keyframe values.
  31786. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31787. */
  31788. constructor( name, times, values, interpolation ) {
  31789. super( name, times, values, interpolation );
  31790. }
  31791. /**
  31792. * Overwritten so the method returns Quaternion based interpolant.
  31793. *
  31794. * @static
  31795. * @param {TypedArray} [result] - The result buffer.
  31796. * @return {QuaternionLinearInterpolant} The new interpolant.
  31797. */
  31798. InterpolantFactoryMethodLinear( result ) {
  31799. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31800. }
  31801. }
  31802. /**
  31803. * The value type name.
  31804. *
  31805. * @type {string}
  31806. * @default 'quaternion'
  31807. */
  31808. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31809. // ValueBufferType is inherited
  31810. // DefaultInterpolation is inherited;
  31811. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31812. /**
  31813. * A track for string keyframe values.
  31814. *
  31815. * @augments KeyframeTrack
  31816. */
  31817. class StringKeyframeTrack extends KeyframeTrack {
  31818. /**
  31819. * Constructs a new string keyframe track.
  31820. *
  31821. * This keyframe track type has no `interpolation` parameter because the
  31822. * interpolation is always discrete.
  31823. *
  31824. * @param {string} name - The keyframe track's name.
  31825. * @param {Array<number>} times - A list of keyframe times.
  31826. * @param {Array<string>} values - A list of keyframe values.
  31827. */
  31828. constructor( name, times, values ) {
  31829. super( name, times, values );
  31830. }
  31831. }
  31832. /**
  31833. * The value type name.
  31834. *
  31835. * @type {string}
  31836. * @default 'string'
  31837. */
  31838. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31839. /**
  31840. * The value buffer type of this keyframe track.
  31841. *
  31842. * @type {TypedArray|Array}
  31843. * @default Array.constructor
  31844. */
  31845. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31846. /**
  31847. * The default interpolation type of this keyframe track.
  31848. *
  31849. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31850. * @default InterpolateDiscrete
  31851. */
  31852. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31853. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31854. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31855. /**
  31856. * A track for vector keyframe values.
  31857. *
  31858. * @augments KeyframeTrack
  31859. */
  31860. class VectorKeyframeTrack extends KeyframeTrack {
  31861. /**
  31862. * Constructs a new vector keyframe track.
  31863. *
  31864. * @param {string} name - The keyframe track's name.
  31865. * @param {Array<number>} times - A list of keyframe times.
  31866. * @param {Array<number>} values - A list of keyframe values.
  31867. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31868. */
  31869. constructor( name, times, values, interpolation ) {
  31870. super( name, times, values, interpolation );
  31871. }
  31872. }
  31873. /**
  31874. * The value type name.
  31875. *
  31876. * @type {string}
  31877. * @default 'vector'
  31878. */
  31879. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31880. /**
  31881. * A reusable set of keyframe tracks which represent an animation.
  31882. */
  31883. class AnimationClip {
  31884. /**
  31885. * Constructs a new animation clip.
  31886. *
  31887. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31888. * use the static interface of this class for creating clips. In most cases though, animation clips
  31889. * will automatically be created by loaders when importing animated 3D assets.
  31890. *
  31891. * @param {string} [name=''] - The clip's name.
  31892. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31893. * the duration will be calculated from the passed keyframes.
  31894. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31895. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31896. * is blended/combined when two or more animations are simultaneously played.
  31897. */
  31898. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31899. /**
  31900. * The clip's name.
  31901. *
  31902. * @type {string}
  31903. */
  31904. this.name = name;
  31905. /**
  31906. * An array of keyframe tracks.
  31907. *
  31908. * @type {Array<KeyframeTrack>}
  31909. */
  31910. this.tracks = tracks;
  31911. /**
  31912. * The clip's duration in seconds.
  31913. *
  31914. * @type {number}
  31915. */
  31916. this.duration = duration;
  31917. /**
  31918. * Defines how the animation is blended/combined when two or more animations
  31919. * are simultaneously played.
  31920. *
  31921. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31922. */
  31923. this.blendMode = blendMode;
  31924. /**
  31925. * The UUID of the animation clip.
  31926. *
  31927. * @type {string}
  31928. * @readonly
  31929. */
  31930. this.uuid = generateUUID();
  31931. /**
  31932. * An object that can be used to store custom data about the animation clip.
  31933. * It should not hold references to functions as these will not be cloned.
  31934. *
  31935. * @type {Object}
  31936. */
  31937. this.userData = {};
  31938. // this means it should figure out its duration by scanning the tracks
  31939. if ( this.duration < 0 ) {
  31940. this.resetDuration();
  31941. }
  31942. }
  31943. /**
  31944. * Factory method for creating an animation clip from the given JSON.
  31945. *
  31946. * @static
  31947. * @param {Object} json - The serialized animation clip.
  31948. * @return {AnimationClip} The new animation clip.
  31949. */
  31950. static parse( json ) {
  31951. const tracks = [],
  31952. jsonTracks = json.tracks,
  31953. frameTime = 1.0 / ( json.fps || 1.0 );
  31954. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31955. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31956. }
  31957. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31958. clip.uuid = json.uuid;
  31959. clip.userData = JSON.parse( json.userData || '{}' );
  31960. return clip;
  31961. }
  31962. /**
  31963. * Serializes the given animation clip into JSON.
  31964. *
  31965. * @static
  31966. * @param {AnimationClip} clip - The animation clip to serialize.
  31967. * @return {Object} The JSON object.
  31968. */
  31969. static toJSON( clip ) {
  31970. const tracks = [],
  31971. clipTracks = clip.tracks;
  31972. const json = {
  31973. 'name': clip.name,
  31974. 'duration': clip.duration,
  31975. 'tracks': tracks,
  31976. 'uuid': clip.uuid,
  31977. 'blendMode': clip.blendMode,
  31978. 'userData': JSON.stringify( clip.userData ),
  31979. };
  31980. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31981. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31982. }
  31983. return json;
  31984. }
  31985. /**
  31986. * Returns a new animation clip from the passed morph targets array of a
  31987. * geometry, taking a name and the number of frames per second.
  31988. *
  31989. * Note: The fps parameter is required, but the animation speed can be
  31990. * overridden via {@link AnimationAction#setDuration}.
  31991. *
  31992. * @static
  31993. * @param {string} name - The name of the animation clip.
  31994. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31995. * @param {number} fps - The Frames-Per-Second value.
  31996. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31997. * @return {AnimationClip} The new animation clip.
  31998. */
  31999. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  32000. const numMorphTargets = morphTargetSequence.length;
  32001. const tracks = [];
  32002. for ( let i = 0; i < numMorphTargets; i ++ ) {
  32003. let times = [];
  32004. let values = [];
  32005. times.push(
  32006. ( i + numMorphTargets - 1 ) % numMorphTargets,
  32007. i,
  32008. ( i + 1 ) % numMorphTargets );
  32009. values.push( 0, 1, 0 );
  32010. const order = getKeyframeOrder( times );
  32011. times = sortedArray( times, 1, order );
  32012. values = sortedArray( values, 1, order );
  32013. // if there is a key at the first frame, duplicate it as the
  32014. // last frame as well for perfect loop.
  32015. if ( ! noLoop && times[ 0 ] === 0 ) {
  32016. times.push( numMorphTargets );
  32017. values.push( values[ 0 ] );
  32018. }
  32019. tracks.push(
  32020. new NumberKeyframeTrack(
  32021. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  32022. times, values
  32023. ).scale( 1.0 / fps ) );
  32024. }
  32025. return new this( name, -1, tracks );
  32026. }
  32027. /**
  32028. * Searches for an animation clip by name, taking as its first parameter
  32029. * either an array of clips, or a mesh or geometry that contains an
  32030. * array named "animations" property.
  32031. *
  32032. * @static
  32033. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  32034. * @param {string} name - The name to search for.
  32035. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  32036. */
  32037. static findByName( objectOrClipArray, name ) {
  32038. let clipArray = objectOrClipArray;
  32039. if ( ! Array.isArray( objectOrClipArray ) ) {
  32040. const o = objectOrClipArray;
  32041. clipArray = o.geometry && o.geometry.animations || o.animations;
  32042. }
  32043. for ( let i = 0; i < clipArray.length; i ++ ) {
  32044. if ( clipArray[ i ].name === name ) {
  32045. return clipArray[ i ];
  32046. }
  32047. }
  32048. return null;
  32049. }
  32050. /**
  32051. * Returns an array of new AnimationClips created from the morph target
  32052. * sequences of a geometry, trying to sort morph target names into
  32053. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  32054. *
  32055. * See {@link MD2Loader#parse} as an example for how the method should be used.
  32056. *
  32057. * @static
  32058. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  32059. * @param {number} fps - The Frames-Per-Second value.
  32060. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  32061. * @return {Array<AnimationClip>} An array of new animation clips.
  32062. */
  32063. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  32064. const animationToMorphTargets = {};
  32065. // tested with https://regex101.com/ on trick sequences
  32066. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  32067. const pattern = /^([\w-]*?)([\d]+)$/;
  32068. // sort morph target names into animation groups based
  32069. // patterns like Walk_001, Walk_002, Run_001, Run_002
  32070. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  32071. const morphTarget = morphTargets[ i ];
  32072. const parts = morphTarget.name.match( pattern );
  32073. if ( parts && parts.length > 1 ) {
  32074. const name = parts[ 1 ];
  32075. let animationMorphTargets = animationToMorphTargets[ name ];
  32076. if ( ! animationMorphTargets ) {
  32077. animationToMorphTargets[ name ] = animationMorphTargets = [];
  32078. }
  32079. animationMorphTargets.push( morphTarget );
  32080. }
  32081. }
  32082. const clips = [];
  32083. for ( const name in animationToMorphTargets ) {
  32084. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  32085. }
  32086. return clips;
  32087. }
  32088. /**
  32089. * Parses the `animation.hierarchy` format and returns a new animation clip.
  32090. *
  32091. * @static
  32092. * @deprecated since r175.
  32093. * @param {Object} animation - A serialized animation clip as JSON.
  32094. * @param {Array<Bone>} bones - An array of bones.
  32095. * @return {?AnimationClip} The new animation clip.
  32096. */
  32097. static parseAnimation( animation, bones ) {
  32098. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  32099. if ( ! animation ) {
  32100. error( 'AnimationClip: No animation in JSONLoader data.' );
  32101. return null;
  32102. }
  32103. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  32104. // only return track if there are actually keys.
  32105. if ( animationKeys.length !== 0 ) {
  32106. const times = [];
  32107. const values = [];
  32108. flattenJSON( animationKeys, times, values, propertyName );
  32109. // empty keys are filtered out, so check again
  32110. if ( times.length !== 0 ) {
  32111. destTracks.push( new trackType( trackName, times, values ) );
  32112. }
  32113. }
  32114. };
  32115. const tracks = [];
  32116. const clipName = animation.name || 'default';
  32117. const fps = animation.fps || 30;
  32118. const blendMode = animation.blendMode;
  32119. // automatic length determination in AnimationClip.
  32120. let duration = animation.length || -1;
  32121. const hierarchyTracks = animation.hierarchy || [];
  32122. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  32123. const animationKeys = hierarchyTracks[ h ].keys;
  32124. // skip empty tracks
  32125. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  32126. // process morph targets
  32127. if ( animationKeys[ 0 ].morphTargets ) {
  32128. // figure out all morph targets used in this track
  32129. const morphTargetNames = {};
  32130. let k;
  32131. for ( k = 0; k < animationKeys.length; k ++ ) {
  32132. if ( animationKeys[ k ].morphTargets ) {
  32133. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  32134. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  32135. }
  32136. }
  32137. }
  32138. // create a track for each morph target with all zero
  32139. // morphTargetInfluences except for the keys in which
  32140. // the morphTarget is named.
  32141. for ( const morphTargetName in morphTargetNames ) {
  32142. const times = [];
  32143. const values = [];
  32144. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  32145. const animationKey = animationKeys[ k ];
  32146. times.push( animationKey.time );
  32147. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  32148. }
  32149. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  32150. }
  32151. duration = morphTargetNames.length * fps;
  32152. } else {
  32153. // ...assume skeletal animation
  32154. const boneName = '.bones[' + bones[ h ].name + ']';
  32155. addNonemptyTrack(
  32156. VectorKeyframeTrack, boneName + '.position',
  32157. animationKeys, 'pos', tracks );
  32158. addNonemptyTrack(
  32159. QuaternionKeyframeTrack, boneName + '.quaternion',
  32160. animationKeys, 'rot', tracks );
  32161. addNonemptyTrack(
  32162. VectorKeyframeTrack, boneName + '.scale',
  32163. animationKeys, 'scl', tracks );
  32164. }
  32165. }
  32166. if ( tracks.length === 0 ) {
  32167. return null;
  32168. }
  32169. const clip = new this( clipName, duration, tracks, blendMode );
  32170. return clip;
  32171. }
  32172. /**
  32173. * Sets the duration of this clip to the duration of its longest keyframe track.
  32174. *
  32175. * @return {AnimationClip} A reference to this animation clip.
  32176. */
  32177. resetDuration() {
  32178. const tracks = this.tracks;
  32179. let duration = 0;
  32180. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  32181. const track = this.tracks[ i ];
  32182. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  32183. }
  32184. this.duration = duration;
  32185. return this;
  32186. }
  32187. /**
  32188. * Trims all tracks to the clip's duration.
  32189. *
  32190. * @return {AnimationClip} A reference to this animation clip.
  32191. */
  32192. trim() {
  32193. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32194. this.tracks[ i ].trim( 0, this.duration );
  32195. }
  32196. return this;
  32197. }
  32198. /**
  32199. * Performs minimal validation on each track in the clip. Returns `true` if all
  32200. * tracks are valid.
  32201. *
  32202. * @return {boolean} Whether the clip's keyframes are valid or not.
  32203. */
  32204. validate() {
  32205. let valid = true;
  32206. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32207. valid = valid && this.tracks[ i ].validate();
  32208. }
  32209. return valid;
  32210. }
  32211. /**
  32212. * Optimizes each track by removing equivalent sequential keys (which are
  32213. * common in morph target sequences).
  32214. *
  32215. * @return {AnimationClip} A reference to this animation clip.
  32216. */
  32217. optimize() {
  32218. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32219. this.tracks[ i ].optimize();
  32220. }
  32221. return this;
  32222. }
  32223. /**
  32224. * Returns a new animation clip with copied values from this instance.
  32225. *
  32226. * @return {AnimationClip} A clone of this instance.
  32227. */
  32228. clone() {
  32229. const tracks = [];
  32230. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32231. tracks.push( this.tracks[ i ].clone() );
  32232. }
  32233. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  32234. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  32235. return clip;
  32236. }
  32237. /**
  32238. * Serializes this animation clip into JSON.
  32239. *
  32240. * @return {Object} The JSON object.
  32241. */
  32242. toJSON() {
  32243. return this.constructor.toJSON( this );
  32244. }
  32245. }
  32246. function getTrackTypeForValueTypeName( typeName ) {
  32247. switch ( typeName.toLowerCase() ) {
  32248. case 'scalar':
  32249. case 'double':
  32250. case 'float':
  32251. case 'number':
  32252. case 'integer':
  32253. return NumberKeyframeTrack;
  32254. case 'vector':
  32255. case 'vector2':
  32256. case 'vector3':
  32257. case 'vector4':
  32258. return VectorKeyframeTrack;
  32259. case 'color':
  32260. return ColorKeyframeTrack;
  32261. case 'quaternion':
  32262. return QuaternionKeyframeTrack;
  32263. case 'bool':
  32264. case 'boolean':
  32265. return BooleanKeyframeTrack;
  32266. case 'string':
  32267. return StringKeyframeTrack;
  32268. }
  32269. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  32270. }
  32271. function parseKeyframeTrack( json ) {
  32272. if ( json.type === undefined ) {
  32273. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  32274. }
  32275. const trackType = getTrackTypeForValueTypeName( json.type );
  32276. if ( json.times === undefined ) {
  32277. const times = [], values = [];
  32278. flattenJSON( json.keys, times, values, 'value' );
  32279. json.times = times;
  32280. json.values = values;
  32281. }
  32282. // derived classes can define a static parse method
  32283. if ( trackType.parse !== undefined ) {
  32284. return trackType.parse( json );
  32285. } else {
  32286. // by default, we assume a constructor compatible with the base
  32287. return new trackType( json.name, json.times, json.values, json.interpolation );
  32288. }
  32289. }
  32290. /**
  32291. * @class
  32292. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  32293. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  32294. * @hideconstructor
  32295. */
  32296. const Cache = {
  32297. /**
  32298. * Whether caching is enabled or not.
  32299. *
  32300. * @static
  32301. * @type {boolean}
  32302. * @default false
  32303. */
  32304. enabled: false,
  32305. /**
  32306. * A dictionary that holds cached files.
  32307. *
  32308. * @static
  32309. * @type {Object<string,Object>}
  32310. */
  32311. files: {},
  32312. /**
  32313. * Adds a cache entry with a key to reference the file. If this key already
  32314. * holds a file, it is overwritten.
  32315. *
  32316. * @static
  32317. * @param {string} key - The key to reference the cached file.
  32318. * @param {Object} file - The file to be cached.
  32319. */
  32320. add: function ( key, file ) {
  32321. if ( this.enabled === false ) return;
  32322. // log( 'Cache', 'Adding key:', key );
  32323. this.files[ key ] = file;
  32324. },
  32325. /**
  32326. * Gets the cached value for the given key.
  32327. *
  32328. * @static
  32329. * @param {string} key - The key to reference the cached file.
  32330. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  32331. */
  32332. get: function ( key ) {
  32333. if ( this.enabled === false ) return;
  32334. // log( 'Cache', 'Checking key:', key );
  32335. return this.files[ key ];
  32336. },
  32337. /**
  32338. * Removes the cached file associated with the given key.
  32339. *
  32340. * @static
  32341. * @param {string} key - The key to reference the cached file.
  32342. */
  32343. remove: function ( key ) {
  32344. delete this.files[ key ];
  32345. },
  32346. /**
  32347. * Remove all values from the cache.
  32348. *
  32349. * @static
  32350. */
  32351. clear: function () {
  32352. this.files = {};
  32353. }
  32354. };
  32355. /**
  32356. * Handles and keeps track of loaded and pending data. A default global
  32357. * instance of this class is created and used by loaders if not supplied
  32358. * manually.
  32359. *
  32360. * In general that should be sufficient, however there are times when it can
  32361. * be useful to have separate loaders - for example if you want to show
  32362. * separate loading bars for objects and textures.
  32363. *
  32364. * ```js
  32365. * const manager = new THREE.LoadingManager();
  32366. * manager.onLoad = () => console.log( 'Loading complete!' );
  32367. *
  32368. * const loader1 = new OBJLoader( manager );
  32369. * const loader2 = new ColladaLoader( manager );
  32370. * ```
  32371. */
  32372. class LoadingManager {
  32373. /**
  32374. * Constructs a new loading manager.
  32375. *
  32376. * @param {Function} [onLoad] - Executes when all items have been loaded.
  32377. * @param {Function} [onProgress] - Executes when single items have been loaded.
  32378. * @param {Function} [onError] - Executes when an error occurs.
  32379. */
  32380. constructor( onLoad, onProgress, onError ) {
  32381. const scope = this;
  32382. let isLoading = false;
  32383. let itemsLoaded = 0;
  32384. let itemsTotal = 0;
  32385. let urlModifier = undefined;
  32386. const handlers = [];
  32387. // Refer to #5689 for the reason why we don't set .onStart
  32388. // in the constructor
  32389. /**
  32390. * Executes when an item starts loading.
  32391. *
  32392. * @type {Function|undefined}
  32393. * @default undefined
  32394. */
  32395. this.onStart = undefined;
  32396. /**
  32397. * Executes when all items have been loaded.
  32398. *
  32399. * @type {Function|undefined}
  32400. * @default undefined
  32401. */
  32402. this.onLoad = onLoad;
  32403. /**
  32404. * Executes when single items have been loaded.
  32405. *
  32406. * @type {Function|undefined}
  32407. * @default undefined
  32408. */
  32409. this.onProgress = onProgress;
  32410. /**
  32411. * Executes when an error occurs.
  32412. *
  32413. * @type {Function|undefined}
  32414. * @default undefined
  32415. */
  32416. this.onError = onError;
  32417. /**
  32418. * Used for aborting ongoing requests in loaders using this manager.
  32419. *
  32420. * @private
  32421. * @type {AbortController | null}
  32422. */
  32423. this._abortController = null;
  32424. /**
  32425. * This should be called by any loader using the manager when the loader
  32426. * starts loading an item.
  32427. *
  32428. * @param {string} url - The URL to load.
  32429. */
  32430. this.itemStart = function ( url ) {
  32431. itemsTotal ++;
  32432. if ( isLoading === false ) {
  32433. if ( scope.onStart !== undefined ) {
  32434. scope.onStart( url, itemsLoaded, itemsTotal );
  32435. }
  32436. }
  32437. isLoading = true;
  32438. };
  32439. /**
  32440. * This should be called by any loader using the manager when the loader
  32441. * ended loading an item.
  32442. *
  32443. * @param {string} url - The URL of the loaded item.
  32444. */
  32445. this.itemEnd = function ( url ) {
  32446. itemsLoaded ++;
  32447. if ( scope.onProgress !== undefined ) {
  32448. scope.onProgress( url, itemsLoaded, itemsTotal );
  32449. }
  32450. if ( itemsLoaded === itemsTotal ) {
  32451. isLoading = false;
  32452. if ( scope.onLoad !== undefined ) {
  32453. scope.onLoad();
  32454. }
  32455. }
  32456. };
  32457. /**
  32458. * This should be called by any loader using the manager when the loader
  32459. * encounters an error when loading an item.
  32460. *
  32461. * @param {string} url - The URL of the item that produces an error.
  32462. */
  32463. this.itemError = function ( url ) {
  32464. if ( scope.onError !== undefined ) {
  32465. scope.onError( url );
  32466. }
  32467. };
  32468. /**
  32469. * Given a URL, uses the URL modifier callback (if any) and returns a
  32470. * resolved URL. If no URL modifier is set, returns the original URL.
  32471. *
  32472. * @param {string} url - The URL to load.
  32473. * @return {string} The resolved URL.
  32474. */
  32475. this.resolveURL = function ( url ) {
  32476. if ( urlModifier ) {
  32477. return urlModifier( url );
  32478. }
  32479. return url;
  32480. };
  32481. /**
  32482. * If provided, the callback will be passed each resource URL before a
  32483. * request is sent. The callback may return the original URL, or a new URL to
  32484. * override loading behavior. This behavior can be used to load assets from
  32485. * .ZIP files, drag-and-drop APIs, and Data URIs.
  32486. *
  32487. * ```js
  32488. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  32489. *
  32490. * const manager = new THREE.LoadingManager();
  32491. *
  32492. * // Initialize loading manager with URL callback.
  32493. * const objectURLs = [];
  32494. * manager.setURLModifier( ( url ) => {
  32495. *
  32496. * url = URL.createObjectURL( blobs[ url ] );
  32497. * objectURLs.push( url );
  32498. * return url;
  32499. *
  32500. * } );
  32501. *
  32502. * // Load as usual, then revoke the blob URLs.
  32503. * const loader = new GLTFLoader( manager );
  32504. * loader.load( 'fish.gltf', (gltf) => {
  32505. *
  32506. * scene.add( gltf.scene );
  32507. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32508. *
  32509. * } );
  32510. * ```
  32511. *
  32512. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32513. * @return {LoadingManager} A reference to this loading manager.
  32514. */
  32515. this.setURLModifier = function ( transform ) {
  32516. urlModifier = transform;
  32517. return this;
  32518. };
  32519. /**
  32520. * Registers a loader with the given regular expression. Can be used to
  32521. * define what loader should be used in order to load specific files. A
  32522. * typical use case is to overwrite the default loader for textures.
  32523. *
  32524. * ```js
  32525. * // add handler for TGA textures
  32526. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32527. * ```
  32528. *
  32529. * @param {string} regex - A regular expression.
  32530. * @param {Loader} loader - A loader that should handle matched cases.
  32531. * @return {LoadingManager} A reference to this loading manager.
  32532. */
  32533. this.addHandler = function ( regex, loader ) {
  32534. handlers.push( regex, loader );
  32535. return this;
  32536. };
  32537. /**
  32538. * Removes the loader for the given regular expression.
  32539. *
  32540. * @param {string} regex - A regular expression.
  32541. * @return {LoadingManager} A reference to this loading manager.
  32542. */
  32543. this.removeHandler = function ( regex ) {
  32544. const index = handlers.indexOf( regex );
  32545. if ( index !== -1 ) {
  32546. handlers.splice( index, 2 );
  32547. }
  32548. return this;
  32549. };
  32550. /**
  32551. * Can be used to retrieve the registered loader for the given file path.
  32552. *
  32553. * @param {string} file - The file path.
  32554. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32555. */
  32556. this.getHandler = function ( file ) {
  32557. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32558. const regex = handlers[ i ];
  32559. const loader = handlers[ i + 1 ];
  32560. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32561. if ( regex.test( file ) ) {
  32562. return loader;
  32563. }
  32564. }
  32565. return null;
  32566. };
  32567. /**
  32568. * Can be used to abort ongoing loading requests in loaders using this manager.
  32569. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32570. * is supported in the browser.
  32571. *
  32572. * @return {LoadingManager} A reference to this loading manager.
  32573. */
  32574. this.abort = function () {
  32575. this.abortController.abort();
  32576. this._abortController = null;
  32577. return this;
  32578. };
  32579. }
  32580. // TODO: Revert this back to a single member variable once this issue has been fixed
  32581. // https://github.com/cloudflare/workerd/issues/3657
  32582. /**
  32583. * Used for aborting ongoing requests in loaders using this manager.
  32584. *
  32585. * @type {AbortController}
  32586. */
  32587. get abortController() {
  32588. if ( ! this._abortController ) {
  32589. this._abortController = new AbortController();
  32590. }
  32591. return this._abortController;
  32592. }
  32593. }
  32594. /**
  32595. * The global default loading manager.
  32596. *
  32597. * @constant
  32598. * @type {LoadingManager}
  32599. */
  32600. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32601. /**
  32602. * Abstract base class for loaders.
  32603. *
  32604. * @abstract
  32605. */
  32606. class Loader {
  32607. /**
  32608. * Constructs a new loader.
  32609. *
  32610. * @param {LoadingManager} [manager] - The loading manager.
  32611. */
  32612. constructor( manager ) {
  32613. /**
  32614. * The loading manager.
  32615. *
  32616. * @type {LoadingManager}
  32617. * @default DefaultLoadingManager
  32618. */
  32619. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32620. /**
  32621. * The crossOrigin string to implement CORS for loading the url from a
  32622. * different domain that allows CORS.
  32623. *
  32624. * @type {string}
  32625. * @default 'anonymous'
  32626. */
  32627. this.crossOrigin = 'anonymous';
  32628. /**
  32629. * Whether the XMLHttpRequest uses credentials.
  32630. *
  32631. * @type {boolean}
  32632. * @default false
  32633. */
  32634. this.withCredentials = false;
  32635. /**
  32636. * The base path from which the asset will be loaded.
  32637. *
  32638. * @type {string}
  32639. */
  32640. this.path = '';
  32641. /**
  32642. * The base path from which additional resources like textures will be loaded.
  32643. *
  32644. * @type {string}
  32645. */
  32646. this.resourcePath = '';
  32647. /**
  32648. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32649. * used in HTTP request.
  32650. *
  32651. * @type {Object<string, any>}
  32652. */
  32653. this.requestHeader = {};
  32654. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32655. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32656. }
  32657. }
  32658. /**
  32659. * This method needs to be implemented by all concrete loaders. It holds the
  32660. * logic for loading assets from the backend.
  32661. *
  32662. * @abstract
  32663. * @param {string} url - The path/URL of the file to be loaded.
  32664. * @param {Function} onLoad - Executed when the loading process has been finished.
  32665. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32666. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32667. */
  32668. load( /* url, onLoad, onProgress, onError */ ) {}
  32669. /**
  32670. * A async version of {@link Loader#load}.
  32671. *
  32672. * @param {string} url - The path/URL of the file to be loaded.
  32673. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32674. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32675. */
  32676. loadAsync( url, onProgress ) {
  32677. const scope = this;
  32678. return new Promise( function ( resolve, reject ) {
  32679. scope.load( url, resolve, onProgress, reject );
  32680. } );
  32681. }
  32682. /**
  32683. * This method needs to be implemented by all concrete loaders. It holds the
  32684. * logic for parsing the asset into three.js entities.
  32685. *
  32686. * @abstract
  32687. * @param {any} data - The data to parse.
  32688. */
  32689. parse( /* data */ ) {}
  32690. /**
  32691. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32692. * from a different domain that allows CORS.
  32693. *
  32694. * @param {string} crossOrigin - The `crossOrigin` value.
  32695. * @return {Loader} A reference to this instance.
  32696. */
  32697. setCrossOrigin( crossOrigin ) {
  32698. this.crossOrigin = crossOrigin;
  32699. return this;
  32700. }
  32701. /**
  32702. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32703. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32704. *
  32705. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32706. *
  32707. * @param {boolean} value - The `withCredentials` value.
  32708. * @return {Loader} A reference to this instance.
  32709. */
  32710. setWithCredentials( value ) {
  32711. this.withCredentials = value;
  32712. return this;
  32713. }
  32714. /**
  32715. * Sets the base path for the asset.
  32716. *
  32717. * @param {string} path - The base path.
  32718. * @return {Loader} A reference to this instance.
  32719. */
  32720. setPath( path ) {
  32721. this.path = path;
  32722. return this;
  32723. }
  32724. /**
  32725. * Sets the base path for dependent resources like textures.
  32726. *
  32727. * @param {string} resourcePath - The resource path.
  32728. * @return {Loader} A reference to this instance.
  32729. */
  32730. setResourcePath( resourcePath ) {
  32731. this.resourcePath = resourcePath;
  32732. return this;
  32733. }
  32734. /**
  32735. * Sets the given request header.
  32736. *
  32737. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32738. * for configuring the HTTP request.
  32739. * @return {Loader} A reference to this instance.
  32740. */
  32741. setRequestHeader( requestHeader ) {
  32742. this.requestHeader = requestHeader;
  32743. return this;
  32744. }
  32745. /**
  32746. * This method can be implemented in loaders for aborting ongoing requests.
  32747. *
  32748. * @abstract
  32749. * @return {Loader} A reference to this instance.
  32750. */
  32751. abort() {
  32752. return this;
  32753. }
  32754. }
  32755. /**
  32756. * Callback for onProgress in loaders.
  32757. *
  32758. * @callback onProgressCallback
  32759. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32760. */
  32761. /**
  32762. * Callback for onError in loaders.
  32763. *
  32764. * @callback onErrorCallback
  32765. * @param {Error} error - The error which occurred during the loading process.
  32766. */
  32767. /**
  32768. * The default material name that is used by loaders
  32769. * when creating materials for loaded 3D objects.
  32770. *
  32771. * Note: Not all loaders might honor this setting.
  32772. *
  32773. * @static
  32774. * @type {string}
  32775. * @default '__DEFAULT'
  32776. */
  32777. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32778. const loading = {};
  32779. class HttpError extends Error {
  32780. constructor( message, response ) {
  32781. super( message );
  32782. this.response = response;
  32783. }
  32784. }
  32785. /**
  32786. * A low level class for loading resources with the Fetch API, used internally by
  32787. * most loaders. It can also be used directly to load any file type that does
  32788. * not have a loader.
  32789. *
  32790. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32791. * once to your application.
  32792. *
  32793. * ```js
  32794. * const loader = new THREE.FileLoader();
  32795. * const data = await loader.loadAsync( 'example.txt' );
  32796. * ```
  32797. *
  32798. * @augments Loader
  32799. */
  32800. class FileLoader extends Loader {
  32801. /**
  32802. * Constructs a new file loader.
  32803. *
  32804. * @param {LoadingManager} [manager] - The loading manager.
  32805. */
  32806. constructor( manager ) {
  32807. super( manager );
  32808. /**
  32809. * The expected mime type. Valid values can be found
  32810. * [here](hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32811. *
  32812. * @type {string}
  32813. */
  32814. this.mimeType = '';
  32815. /**
  32816. * The expected response type.
  32817. *
  32818. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32819. * @default ''
  32820. */
  32821. this.responseType = '';
  32822. /**
  32823. * Used for aborting requests.
  32824. *
  32825. * @private
  32826. * @type {AbortController}
  32827. */
  32828. this._abortController = new AbortController();
  32829. }
  32830. /**
  32831. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32832. *
  32833. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32834. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32835. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32836. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32837. * @return {any|undefined} The cached resource if available.
  32838. */
  32839. load( url, onLoad, onProgress, onError ) {
  32840. if ( url === undefined ) url = '';
  32841. if ( this.path !== undefined ) url = this.path + url;
  32842. url = this.manager.resolveURL( url );
  32843. const cached = Cache.get( `file:${url}` );
  32844. if ( cached !== undefined ) {
  32845. this.manager.itemStart( url );
  32846. setTimeout( () => {
  32847. if ( onLoad ) onLoad( cached );
  32848. this.manager.itemEnd( url );
  32849. }, 0 );
  32850. return cached;
  32851. }
  32852. // Check if request is duplicate
  32853. if ( loading[ url ] !== undefined ) {
  32854. loading[ url ].push( {
  32855. onLoad: onLoad,
  32856. onProgress: onProgress,
  32857. onError: onError
  32858. } );
  32859. return;
  32860. }
  32861. // Initialise array for duplicate requests
  32862. loading[ url ] = [];
  32863. loading[ url ].push( {
  32864. onLoad: onLoad,
  32865. onProgress: onProgress,
  32866. onError: onError,
  32867. } );
  32868. // create request
  32869. const req = new Request( url, {
  32870. headers: new Headers( this.requestHeader ),
  32871. credentials: this.withCredentials ? 'include' : 'same-origin',
  32872. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32873. } );
  32874. // record states ( avoid data race )
  32875. const mimeType = this.mimeType;
  32876. const responseType = this.responseType;
  32877. // start the fetch
  32878. fetch( req )
  32879. .then( response => {
  32880. if ( response.status === 200 || response.status === 0 ) {
  32881. // Some browsers return HTTP Status 0 when using non-http protocol
  32882. // e.g. 'file://' or 'data://'. Handle as success.
  32883. if ( response.status === 0 ) {
  32884. warn( 'FileLoader: HTTP Status 0 received.' );
  32885. }
  32886. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32887. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32888. return response;
  32889. }
  32890. const callbacks = loading[ url ];
  32891. const reader = response.body.getReader();
  32892. // Nginx needs X-File-Size check
  32893. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32894. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32895. const total = contentLength ? parseInt( contentLength ) : 0;
  32896. const lengthComputable = total !== 0;
  32897. let loaded = 0;
  32898. // periodically read data into the new stream tracking while download progress
  32899. const stream = new ReadableStream( {
  32900. start( controller ) {
  32901. readData();
  32902. function readData() {
  32903. reader.read().then( ( { done, value } ) => {
  32904. if ( done ) {
  32905. controller.close();
  32906. } else {
  32907. loaded += value.byteLength;
  32908. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32909. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32910. const callback = callbacks[ i ];
  32911. if ( callback.onProgress ) callback.onProgress( event );
  32912. }
  32913. controller.enqueue( value );
  32914. readData();
  32915. }
  32916. }, ( e ) => {
  32917. controller.error( e );
  32918. } );
  32919. }
  32920. }
  32921. } );
  32922. return new Response( stream );
  32923. } else {
  32924. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32925. }
  32926. } )
  32927. .then( response => {
  32928. switch ( responseType ) {
  32929. case 'arraybuffer':
  32930. return response.arrayBuffer();
  32931. case 'blob':
  32932. return response.blob();
  32933. case 'document':
  32934. return response.text()
  32935. .then( text => {
  32936. const parser = new DOMParser();
  32937. return parser.parseFromString( text, mimeType );
  32938. } );
  32939. case 'json':
  32940. return response.json();
  32941. default:
  32942. if ( mimeType === '' ) {
  32943. return response.text();
  32944. } else {
  32945. // sniff encoding
  32946. const re = /charset="?([^;"\s]*)"?/i;
  32947. const exec = re.exec( mimeType );
  32948. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32949. const decoder = new TextDecoder( label );
  32950. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32951. }
  32952. }
  32953. } )
  32954. .then( data => {
  32955. // Add to cache only on HTTP success, so that we do not cache
  32956. // error response bodies as proper responses to requests.
  32957. Cache.add( `file:${url}`, data );
  32958. const callbacks = loading[ url ];
  32959. delete loading[ url ];
  32960. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32961. const callback = callbacks[ i ];
  32962. if ( callback.onLoad ) callback.onLoad( data );
  32963. }
  32964. } )
  32965. .catch( err => {
  32966. // Abort errors and other errors are handled the same
  32967. const callbacks = loading[ url ];
  32968. if ( callbacks === undefined ) {
  32969. // When onLoad was called and url was deleted in `loading`
  32970. this.manager.itemError( url );
  32971. throw err;
  32972. }
  32973. delete loading[ url ];
  32974. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32975. const callback = callbacks[ i ];
  32976. if ( callback.onError ) callback.onError( err );
  32977. }
  32978. this.manager.itemError( url );
  32979. } )
  32980. .finally( () => {
  32981. this.manager.itemEnd( url );
  32982. } );
  32983. this.manager.itemStart( url );
  32984. }
  32985. /**
  32986. * Sets the expected response type.
  32987. *
  32988. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32989. * @return {FileLoader} A reference to this file loader.
  32990. */
  32991. setResponseType( value ) {
  32992. this.responseType = value;
  32993. return this;
  32994. }
  32995. /**
  32996. * Sets the expected mime type of the loaded file.
  32997. *
  32998. * @param {string} value - The mime type.
  32999. * @return {FileLoader} A reference to this file loader.
  33000. */
  33001. setMimeType( value ) {
  33002. this.mimeType = value;
  33003. return this;
  33004. }
  33005. /**
  33006. * Aborts ongoing fetch requests.
  33007. *
  33008. * @return {FileLoader} A reference to this instance.
  33009. */
  33010. abort() {
  33011. this._abortController.abort();
  33012. this._abortController = new AbortController();
  33013. return this;
  33014. }
  33015. }
  33016. /**
  33017. * Class for loading animation clips in the JSON format. The files are internally
  33018. * loaded via {@link FileLoader}.
  33019. *
  33020. * ```js
  33021. * const loader = new THREE.AnimationLoader();
  33022. * const animations = await loader.loadAsync( 'animations/animation.js' );
  33023. * ```
  33024. *
  33025. * @augments Loader
  33026. */
  33027. class AnimationLoader extends Loader {
  33028. /**
  33029. * Constructs a new animation 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 pass the loaded animations as an array
  33038. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  33039. *
  33040. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33041. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  33042. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33043. * @param {onErrorCallback} onError - Executed when errors occur.
  33044. */
  33045. load( url, onLoad, onProgress, onError ) {
  33046. const scope = this;
  33047. const loader = new FileLoader( this.manager );
  33048. loader.setPath( this.path );
  33049. loader.setRequestHeader( this.requestHeader );
  33050. loader.setWithCredentials( this.withCredentials );
  33051. loader.load( url, function ( text ) {
  33052. try {
  33053. onLoad( scope.parse( JSON.parse( text ) ) );
  33054. } catch ( e ) {
  33055. if ( onError ) {
  33056. onError( e );
  33057. } else {
  33058. error( e );
  33059. }
  33060. scope.manager.itemError( url );
  33061. }
  33062. }, onProgress, onError );
  33063. }
  33064. /**
  33065. * Parses the given JSON object and returns an array of animation clips.
  33066. *
  33067. * @param {Object} json - The serialized animation clips.
  33068. * @return {Array<AnimationClip>} The parsed animation clips.
  33069. */
  33070. parse( json ) {
  33071. const animations = [];
  33072. for ( let i = 0; i < json.length; i ++ ) {
  33073. const clip = AnimationClip.parse( json[ i ] );
  33074. animations.push( clip );
  33075. }
  33076. return animations;
  33077. }
  33078. }
  33079. /**
  33080. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  33081. * Textures are internally loaded via {@link FileLoader}.
  33082. *
  33083. * Derived classes have to implement the `parse()` method which holds the parsing
  33084. * for the respective format.
  33085. *
  33086. * @abstract
  33087. * @augments Loader
  33088. */
  33089. class CompressedTextureLoader extends Loader {
  33090. /**
  33091. * Constructs a new compressed texture loader.
  33092. *
  33093. * @param {LoadingManager} [manager] - The loading manager.
  33094. */
  33095. constructor( manager ) {
  33096. super( manager );
  33097. }
  33098. /**
  33099. * Starts loading from the given URL and passes the loaded compressed texture
  33100. * to the `onLoad()` callback. The method also returns a new texture object which can
  33101. * directly be used for material creation. If you do it this way, the texture
  33102. * may pop up in your scene once the respective loading process is finished.
  33103. *
  33104. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33105. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  33106. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33107. * @param {onErrorCallback} onError - Executed when errors occur.
  33108. * @return {CompressedTexture} The compressed texture.
  33109. */
  33110. load( url, onLoad, onProgress, onError ) {
  33111. const scope = this;
  33112. const images = [];
  33113. const texture = new CompressedTexture();
  33114. const loader = new FileLoader( this.manager );
  33115. loader.setPath( this.path );
  33116. loader.setResponseType( 'arraybuffer' );
  33117. loader.setRequestHeader( this.requestHeader );
  33118. loader.setWithCredentials( scope.withCredentials );
  33119. let loaded = 0;
  33120. function loadTexture( i ) {
  33121. loader.load( url[ i ], function ( buffer ) {
  33122. const texDatas = scope.parse( buffer, true );
  33123. images[ i ] = {
  33124. width: texDatas.width,
  33125. height: texDatas.height,
  33126. format: texDatas.format,
  33127. mipmaps: texDatas.mipmaps
  33128. };
  33129. loaded += 1;
  33130. if ( loaded === 6 ) {
  33131. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  33132. texture.image = images;
  33133. texture.format = texDatas.format;
  33134. texture.needsUpdate = true;
  33135. if ( onLoad ) onLoad( texture );
  33136. }
  33137. }, onProgress, onError );
  33138. }
  33139. if ( Array.isArray( url ) ) {
  33140. for ( let i = 0, il = url.length; i < il; ++ i ) {
  33141. loadTexture( i );
  33142. }
  33143. } else {
  33144. // compressed cubemap texture stored in a single DDS file
  33145. loader.load( url, function ( buffer ) {
  33146. const texDatas = scope.parse( buffer, true );
  33147. if ( texDatas.isCubemap ) {
  33148. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  33149. for ( let f = 0; f < faces; f ++ ) {
  33150. images[ f ] = { mipmaps: [] };
  33151. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  33152. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  33153. images[ f ].format = texDatas.format;
  33154. images[ f ].width = texDatas.width;
  33155. images[ f ].height = texDatas.height;
  33156. }
  33157. }
  33158. texture.image = images;
  33159. } else {
  33160. texture.image.width = texDatas.width;
  33161. texture.image.height = texDatas.height;
  33162. texture.mipmaps = texDatas.mipmaps;
  33163. }
  33164. if ( texDatas.mipmapCount === 1 ) {
  33165. texture.minFilter = LinearFilter;
  33166. }
  33167. texture.format = texDatas.format;
  33168. texture.needsUpdate = true;
  33169. if ( onLoad ) onLoad( texture );
  33170. }, onProgress, onError );
  33171. }
  33172. return texture;
  33173. }
  33174. }
  33175. const _loading = new WeakMap();
  33176. /**
  33177. * A loader for loading images. The class loads images with the HTML `Image` API.
  33178. *
  33179. * ```js
  33180. * const loader = new THREE.ImageLoader();
  33181. * const image = await loader.loadAsync( 'image.png' );
  33182. * ```
  33183. * Please note that `ImageLoader` has dropped support for progress
  33184. * events in `r84`. For an `ImageLoader` that supports progress events, see
  33185. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  33186. *
  33187. * @augments Loader
  33188. */
  33189. class ImageLoader extends Loader {
  33190. /**
  33191. * Constructs a new image loader.
  33192. *
  33193. * @param {LoadingManager} [manager] - The loading manager.
  33194. */
  33195. constructor( manager ) {
  33196. super( manager );
  33197. }
  33198. /**
  33199. * Starts loading from the given URL and passes the loaded image
  33200. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  33201. * directly be used for texture creation. If you do it this way, the texture
  33202. * may pop up in your scene once the respective loading process is finished.
  33203. *
  33204. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33205. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  33206. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33207. * @param {onErrorCallback} onError - Executed when errors occur.
  33208. * @return {Image} The image.
  33209. */
  33210. load( url, onLoad, onProgress, onError ) {
  33211. if ( this.path !== undefined ) url = this.path + url;
  33212. url = this.manager.resolveURL( url );
  33213. const scope = this;
  33214. const cached = Cache.get( `image:${url}` );
  33215. if ( cached !== undefined ) {
  33216. if ( cached.complete === true ) {
  33217. scope.manager.itemStart( url );
  33218. setTimeout( function () {
  33219. if ( onLoad ) onLoad( cached );
  33220. scope.manager.itemEnd( url );
  33221. }, 0 );
  33222. } else {
  33223. let arr = _loading.get( cached );
  33224. if ( arr === undefined ) {
  33225. arr = [];
  33226. _loading.set( cached, arr );
  33227. }
  33228. arr.push( { onLoad, onError } );
  33229. }
  33230. return cached;
  33231. }
  33232. const image = createElementNS( 'img' );
  33233. function onImageLoad() {
  33234. removeEventListeners();
  33235. if ( onLoad ) onLoad( this );
  33236. //
  33237. const callbacks = _loading.get( this ) || [];
  33238. for ( let i = 0; i < callbacks.length; i ++ ) {
  33239. const callback = callbacks[ i ];
  33240. if ( callback.onLoad ) callback.onLoad( this );
  33241. }
  33242. _loading.delete( this );
  33243. scope.manager.itemEnd( url );
  33244. }
  33245. function onImageError( event ) {
  33246. removeEventListeners();
  33247. if ( onError ) onError( event );
  33248. Cache.remove( `image:${url}` );
  33249. //
  33250. const callbacks = _loading.get( this ) || [];
  33251. for ( let i = 0; i < callbacks.length; i ++ ) {
  33252. const callback = callbacks[ i ];
  33253. if ( callback.onError ) callback.onError( event );
  33254. }
  33255. _loading.delete( this );
  33256. scope.manager.itemError( url );
  33257. scope.manager.itemEnd( url );
  33258. }
  33259. function removeEventListeners() {
  33260. image.removeEventListener( 'load', onImageLoad, false );
  33261. image.removeEventListener( 'error', onImageError, false );
  33262. }
  33263. image.addEventListener( 'load', onImageLoad, false );
  33264. image.addEventListener( 'error', onImageError, false );
  33265. if ( url.slice( 0, 5 ) !== 'data:' ) {
  33266. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  33267. }
  33268. Cache.add( `image:${url}`, image );
  33269. scope.manager.itemStart( url );
  33270. image.src = url;
  33271. return image;
  33272. }
  33273. }
  33274. /**
  33275. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  33276. *
  33277. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  33278. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  33279. * like vertical and horizontal cross, column and row layouts are not supported.
  33280. *
  33281. * Note that, by convention, cube maps are specified in a coordinate system
  33282. * in which positive-x is to the right when looking up the positive-z axis --
  33283. * in other words, using a left-handed coordinate system. Since three.js uses
  33284. * a right-handed coordinate system, environment maps used in three.js will
  33285. * have pos-x and neg-x swapped.
  33286. *
  33287. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  33288. * is set to `SRGBColorSpace` by default.
  33289. *
  33290. * ```js
  33291. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  33292. * const cubeTexture = await loader.loadAsync( [
  33293. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  33294. * ] );
  33295. * scene.background = cubeTexture;
  33296. * ```
  33297. *
  33298. * @augments Loader
  33299. */
  33300. class CubeTextureLoader extends Loader {
  33301. /**
  33302. * Constructs a new cube texture loader.
  33303. *
  33304. * @param {LoadingManager} [manager] - The loading manager.
  33305. */
  33306. constructor( manager ) {
  33307. super( manager );
  33308. }
  33309. /**
  33310. * Starts loading from the given URL and pass the fully loaded cube texture
  33311. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  33312. * directly be used for material creation. If you do it this way, the cube texture
  33313. * may pop up in your scene once the respective loading process is finished.
  33314. *
  33315. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  33316. * cube texture. The urls should be specified in the following order: pos-x,
  33317. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  33318. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  33319. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33320. * @param {onErrorCallback} onError - Executed when errors occur.
  33321. * @return {CubeTexture} The cube texture.
  33322. */
  33323. load( urls, onLoad, onProgress, onError ) {
  33324. const texture = new CubeTexture();
  33325. texture.colorSpace = SRGBColorSpace;
  33326. const loader = new ImageLoader( this.manager );
  33327. loader.setCrossOrigin( this.crossOrigin );
  33328. loader.setPath( this.path );
  33329. let loaded = 0;
  33330. function loadTexture( i ) {
  33331. loader.load( urls[ i ], function ( image ) {
  33332. texture.images[ i ] = image;
  33333. loaded ++;
  33334. if ( loaded === 6 ) {
  33335. texture.needsUpdate = true;
  33336. if ( onLoad ) onLoad( texture );
  33337. }
  33338. }, undefined, onError );
  33339. }
  33340. for ( let i = 0; i < urls.length; ++ i ) {
  33341. loadTexture( i );
  33342. }
  33343. return texture;
  33344. }
  33345. }
  33346. /**
  33347. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  33348. * Textures are internally loaded via {@link FileLoader}.
  33349. *
  33350. * Derived classes have to implement the `parse()` method which holds the parsing
  33351. * for the respective format.
  33352. *
  33353. * @abstract
  33354. * @augments Loader
  33355. */
  33356. class DataTextureLoader extends Loader {
  33357. /**
  33358. * Constructs a new data texture loader.
  33359. *
  33360. * @param {LoadingManager} [manager] - The loading manager.
  33361. */
  33362. constructor( manager ) {
  33363. super( manager );
  33364. }
  33365. /**
  33366. * Starts loading from the given URL and passes the loaded data texture
  33367. * to the `onLoad()` callback. The method also returns a new texture object which can
  33368. * directly be used for material creation. If you do it this way, the texture
  33369. * may pop up in your scene once the respective loading process is finished.
  33370. *
  33371. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33372. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  33373. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33374. * @param {onErrorCallback} onError - Executed when errors occur.
  33375. * @return {DataTexture} The data texture.
  33376. */
  33377. load( url, onLoad, onProgress, onError ) {
  33378. const scope = this;
  33379. const texture = new DataTexture();
  33380. const loader = new FileLoader( this.manager );
  33381. loader.setResponseType( 'arraybuffer' );
  33382. loader.setRequestHeader( this.requestHeader );
  33383. loader.setPath( this.path );
  33384. loader.setWithCredentials( scope.withCredentials );
  33385. loader.load( url, function ( buffer ) {
  33386. let texData;
  33387. try {
  33388. texData = scope.parse( buffer );
  33389. } catch ( error ) {
  33390. if ( onError !== undefined ) {
  33391. onError( error );
  33392. } else {
  33393. error( error );
  33394. return;
  33395. }
  33396. }
  33397. if ( texData.image !== undefined ) {
  33398. texture.image = texData.image;
  33399. } else if ( texData.data !== undefined ) {
  33400. texture.image.width = texData.width;
  33401. texture.image.height = texData.height;
  33402. texture.image.data = texData.data;
  33403. }
  33404. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  33405. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  33406. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  33407. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  33408. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  33409. if ( texData.colorSpace !== undefined ) {
  33410. texture.colorSpace = texData.colorSpace;
  33411. }
  33412. if ( texData.flipY !== undefined ) {
  33413. texture.flipY = texData.flipY;
  33414. }
  33415. if ( texData.format !== undefined ) {
  33416. texture.format = texData.format;
  33417. }
  33418. if ( texData.type !== undefined ) {
  33419. texture.type = texData.type;
  33420. }
  33421. if ( texData.mipmaps !== undefined ) {
  33422. texture.mipmaps = texData.mipmaps;
  33423. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  33424. }
  33425. if ( texData.mipmapCount === 1 ) {
  33426. texture.minFilter = LinearFilter;
  33427. }
  33428. if ( texData.generateMipmaps !== undefined ) {
  33429. texture.generateMipmaps = texData.generateMipmaps;
  33430. }
  33431. texture.needsUpdate = true;
  33432. if ( onLoad ) onLoad( texture, texData );
  33433. }, onProgress, onError );
  33434. return texture;
  33435. }
  33436. }
  33437. /**
  33438. * Class for loading textures. Images are internally
  33439. * loaded via {@link ImageLoader}.
  33440. *
  33441. * ```js
  33442. * const loader = new THREE.TextureLoader();
  33443. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  33444. *
  33445. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  33446. * ```
  33447. * Please note that `TextureLoader` has dropped support for progress
  33448. * events in `r84`. For a `TextureLoader` that supports progress events, see
  33449. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  33450. *
  33451. * @augments Loader
  33452. */
  33453. class TextureLoader extends Loader {
  33454. /**
  33455. * Constructs a new texture loader.
  33456. *
  33457. * @param {LoadingManager} [manager] - The loading manager.
  33458. */
  33459. constructor( manager ) {
  33460. super( manager );
  33461. }
  33462. /**
  33463. * Starts loading from the given URL and pass the fully loaded texture
  33464. * to the `onLoad()` callback. The method also returns a new texture object which can
  33465. * directly be used for material creation. If you do it this way, the texture
  33466. * may pop up in your scene once the respective loading process is finished.
  33467. *
  33468. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33469. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  33470. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33471. * @param {onErrorCallback} onError - Executed when errors occur.
  33472. * @return {Texture} The texture.
  33473. */
  33474. load( url, onLoad, onProgress, onError ) {
  33475. const texture = new Texture();
  33476. const loader = new ImageLoader( this.manager );
  33477. loader.setCrossOrigin( this.crossOrigin );
  33478. loader.setPath( this.path );
  33479. loader.load( url, function ( image ) {
  33480. texture.image = image;
  33481. texture.needsUpdate = true;
  33482. if ( onLoad !== undefined ) {
  33483. onLoad( texture );
  33484. }
  33485. }, onProgress, onError );
  33486. return texture;
  33487. }
  33488. }
  33489. /**
  33490. * Abstract base class for lights - all other light types inherit the
  33491. * properties and methods described here.
  33492. *
  33493. * @abstract
  33494. * @augments Object3D
  33495. */
  33496. class Light extends Object3D {
  33497. /**
  33498. * Constructs a new light.
  33499. *
  33500. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33501. * @param {number} [intensity=1] - The light's strength/intensity.
  33502. */
  33503. constructor( color, intensity = 1 ) {
  33504. super();
  33505. /**
  33506. * This flag can be used for type testing.
  33507. *
  33508. * @type {boolean}
  33509. * @readonly
  33510. * @default true
  33511. */
  33512. this.isLight = true;
  33513. this.type = 'Light';
  33514. /**
  33515. * The light's color.
  33516. *
  33517. * @type {Color}
  33518. */
  33519. this.color = new Color( color );
  33520. /**
  33521. * The light's intensity.
  33522. *
  33523. * @type {number}
  33524. * @default 1
  33525. */
  33526. this.intensity = intensity;
  33527. }
  33528. /**
  33529. * Frees the GPU-related resources allocated by this instance. Call this
  33530. * method whenever this instance is no longer used in your app.
  33531. */
  33532. dispose() {
  33533. this.dispatchEvent( { type: 'dispose' } );
  33534. }
  33535. copy( source, recursive ) {
  33536. super.copy( source, recursive );
  33537. this.color.copy( source.color );
  33538. this.intensity = source.intensity;
  33539. return this;
  33540. }
  33541. toJSON( meta ) {
  33542. const data = super.toJSON( meta );
  33543. data.object.color = this.color.getHex();
  33544. data.object.intensity = this.intensity;
  33545. return data;
  33546. }
  33547. }
  33548. /**
  33549. * A light source positioned directly above the scene, with color fading from
  33550. * the sky color to the ground color.
  33551. *
  33552. * This light cannot be used to cast shadows.
  33553. *
  33554. * ```js
  33555. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33556. * scene.add( light );
  33557. * ```
  33558. *
  33559. * @augments Light
  33560. */
  33561. class HemisphereLight extends Light {
  33562. /**
  33563. * Constructs a new hemisphere light.
  33564. *
  33565. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33566. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33567. * @param {number} [intensity=1] - The light's strength/intensity.
  33568. */
  33569. constructor( skyColor, groundColor, intensity ) {
  33570. super( skyColor, intensity );
  33571. /**
  33572. * This flag can be used for type testing.
  33573. *
  33574. * @type {boolean}
  33575. * @readonly
  33576. * @default true
  33577. */
  33578. this.isHemisphereLight = true;
  33579. this.type = 'HemisphereLight';
  33580. this.position.copy( Object3D.DEFAULT_UP );
  33581. this.updateMatrix();
  33582. /**
  33583. * The light's ground color.
  33584. *
  33585. * @type {Color}
  33586. */
  33587. this.groundColor = new Color( groundColor );
  33588. }
  33589. copy( source, recursive ) {
  33590. super.copy( source, recursive );
  33591. this.groundColor.copy( source.groundColor );
  33592. return this;
  33593. }
  33594. toJSON( meta ) {
  33595. const data = super.toJSON( meta );
  33596. data.object.groundColor = this.groundColor.getHex();
  33597. return data;
  33598. }
  33599. }
  33600. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33601. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33602. const _lookTarget = /*@__PURE__*/ new Vector3();
  33603. /**
  33604. * Abstract base class for light shadow classes. These classes
  33605. * represent the shadow configuration for different light types.
  33606. *
  33607. * @abstract
  33608. */
  33609. class LightShadow {
  33610. /**
  33611. * Constructs a new light shadow.
  33612. *
  33613. * @param {Camera} camera - The light's view of the world.
  33614. */
  33615. constructor( camera ) {
  33616. /**
  33617. * The light's view of the world.
  33618. *
  33619. * @type {Camera}
  33620. */
  33621. this.camera = camera;
  33622. /**
  33623. * The intensity of the shadow. The default is `1`.
  33624. * Valid values are in the range `[0, 1]`.
  33625. *
  33626. * @type {number}
  33627. * @default 1
  33628. */
  33629. this.intensity = 1;
  33630. /**
  33631. * Shadow map bias, how much to add or subtract from the normalized depth
  33632. * when deciding whether a surface is in shadow.
  33633. *
  33634. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33635. * may help reduce artifacts in shadows.
  33636. *
  33637. * @type {number}
  33638. * @default 0
  33639. */
  33640. this.bias = 0;
  33641. /**
  33642. * A node version of `bias`. Only supported with `WebGPURenderer`.
  33643. *
  33644. * If a bias node is defined, `bias` has no effect.
  33645. *
  33646. * @type {?Node<float>}
  33647. * @default null
  33648. */
  33649. this.biasNode = null;
  33650. /**
  33651. * Defines how much the position used to query the shadow map is offset along
  33652. * the object normal. The default is `0`. Increasing this value can be used to
  33653. * reduce shadow acne especially in large scenes where light shines onto
  33654. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33655. *
  33656. * @type {number}
  33657. * @default 0
  33658. */
  33659. this.normalBias = 0;
  33660. /**
  33661. * Setting this to values greater than 1 will blur the edges of the shadow.
  33662. * High values will cause unwanted banding effects in the shadows - a greater
  33663. * map size will allow for a higher value to be used here before these effects
  33664. * become visible.
  33665. *
  33666. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33667. *
  33668. * @type {number}
  33669. * @default 1
  33670. */
  33671. this.radius = 1;
  33672. /**
  33673. * The amount of samples to use when blurring a VSM shadow map.
  33674. *
  33675. * @type {number}
  33676. * @default 8
  33677. */
  33678. this.blurSamples = 8;
  33679. /**
  33680. * Defines the width and height of the shadow map. Higher values give better quality
  33681. * shadows at the cost of computation time. Values must be powers of two.
  33682. *
  33683. * @type {Vector2}
  33684. * @default (512,512)
  33685. */
  33686. this.mapSize = new Vector2( 512, 512 );
  33687. /**
  33688. * The type of shadow texture. The default is `UnsignedByteType`.
  33689. *
  33690. * @type {number}
  33691. * @default UnsignedByteType
  33692. */
  33693. this.mapType = UnsignedByteType;
  33694. /**
  33695. * The depth map generated using the internal camera; a location beyond a
  33696. * pixel's depth is in shadow. Computed internally during rendering.
  33697. *
  33698. * @type {?RenderTarget}
  33699. * @default null
  33700. */
  33701. this.map = null;
  33702. /**
  33703. * The distribution map generated using the internal camera; an occlusion is
  33704. * calculated based on the distribution of depths. Computed internally during
  33705. * rendering.
  33706. *
  33707. * @type {?RenderTarget}
  33708. * @default null
  33709. */
  33710. this.mapPass = null;
  33711. /**
  33712. * Model to shadow camera space, to compute location and depth in shadow map.
  33713. * This is computed internally during rendering.
  33714. *
  33715. * @type {Matrix4}
  33716. */
  33717. this.matrix = new Matrix4();
  33718. /**
  33719. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33720. * lighting / shadows, you may set this to `false`.
  33721. *
  33722. * @type {boolean}
  33723. * @default true
  33724. */
  33725. this.autoUpdate = true;
  33726. /**
  33727. * When set to `true`, shadow maps will be updated in the next `render` call.
  33728. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33729. * set this property to `true` and then make a render call to update the light's shadow.
  33730. *
  33731. * @type {boolean}
  33732. * @default false
  33733. */
  33734. this.needsUpdate = false;
  33735. this._frustum = new Frustum();
  33736. this._frameExtents = new Vector2( 1, 1 );
  33737. this._viewportCount = 1;
  33738. this._viewports = [
  33739. new Vector4( 0, 0, 1, 1 )
  33740. ];
  33741. }
  33742. /**
  33743. * Used internally by the renderer to get the number of viewports that need
  33744. * to be rendered for this shadow.
  33745. *
  33746. * @return {number} The viewport count.
  33747. */
  33748. getViewportCount() {
  33749. return this._viewportCount;
  33750. }
  33751. /**
  33752. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33753. *
  33754. * @return {Frustum} The shadow camera frustum.
  33755. */
  33756. getFrustum() {
  33757. return this._frustum;
  33758. }
  33759. /**
  33760. * Update the matrices for the camera and shadow, used internally by the renderer.
  33761. *
  33762. * @param {Light} light - The light for which the shadow is being rendered.
  33763. */
  33764. updateMatrices( light ) {
  33765. const shadowCamera = this.camera;
  33766. const shadowMatrix = this.matrix;
  33767. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33768. shadowCamera.position.copy( _lightPositionWorld );
  33769. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  33770. shadowCamera.lookAt( _lookTarget );
  33771. shadowCamera.updateMatrixWorld();
  33772. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33773. this._frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33774. if ( shadowCamera.reversedDepth ) {
  33775. shadowMatrix.set(
  33776. 0.5, 0.0, 0.0, 0.5,
  33777. 0.0, 0.5, 0.0, 0.5,
  33778. 0.0, 0.0, 1.0, 0.0,
  33779. 0.0, 0.0, 0.0, 1.0
  33780. );
  33781. } else {
  33782. shadowMatrix.set(
  33783. 0.5, 0.0, 0.0, 0.5,
  33784. 0.0, 0.5, 0.0, 0.5,
  33785. 0.0, 0.0, 0.5, 0.5,
  33786. 0.0, 0.0, 0.0, 1.0
  33787. );
  33788. }
  33789. shadowMatrix.multiply( _projScreenMatrix );
  33790. }
  33791. /**
  33792. * Returns a viewport definition for the given viewport index.
  33793. *
  33794. * @param {number} viewportIndex - The viewport index.
  33795. * @return {Vector4} The viewport.
  33796. */
  33797. getViewport( viewportIndex ) {
  33798. return this._viewports[ viewportIndex ];
  33799. }
  33800. /**
  33801. * Returns the frame extends.
  33802. *
  33803. * @return {Vector2} The frame extends.
  33804. */
  33805. getFrameExtents() {
  33806. return this._frameExtents;
  33807. }
  33808. /**
  33809. * Frees the GPU-related resources allocated by this instance. Call this
  33810. * method whenever this instance is no longer used in your app.
  33811. */
  33812. dispose() {
  33813. if ( this.map ) {
  33814. this.map.dispose();
  33815. }
  33816. if ( this.mapPass ) {
  33817. this.mapPass.dispose();
  33818. }
  33819. }
  33820. /**
  33821. * Copies the values of the given light shadow instance to this instance.
  33822. *
  33823. * @param {LightShadow} source - The light shadow to copy.
  33824. * @return {LightShadow} A reference to this light shadow instance.
  33825. */
  33826. copy( source ) {
  33827. this.camera = source.camera.clone();
  33828. this.intensity = source.intensity;
  33829. this.bias = source.bias;
  33830. this.radius = source.radius;
  33831. this.autoUpdate = source.autoUpdate;
  33832. this.needsUpdate = source.needsUpdate;
  33833. this.normalBias = source.normalBias;
  33834. this.blurSamples = source.blurSamples;
  33835. this.mapSize.copy( source.mapSize );
  33836. this.biasNode = source.biasNode;
  33837. return this;
  33838. }
  33839. /**
  33840. * Returns a new light shadow instance with copied values from this instance.
  33841. *
  33842. * @return {LightShadow} A clone of this instance.
  33843. */
  33844. clone() {
  33845. return new this.constructor().copy( this );
  33846. }
  33847. /**
  33848. * Serializes the light shadow into JSON.
  33849. *
  33850. * @return {Object} A JSON object representing the serialized light shadow.
  33851. * @see {@link ObjectLoader#parse}
  33852. */
  33853. toJSON() {
  33854. const object = {};
  33855. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33856. if ( this.bias !== 0 ) object.bias = this.bias;
  33857. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33858. if ( this.radius !== 1 ) object.radius = this.radius;
  33859. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33860. object.camera = this.camera.toJSON( false ).object;
  33861. delete object.camera.matrix;
  33862. return object;
  33863. }
  33864. }
  33865. /**
  33866. * Represents the shadow configuration of directional lights.
  33867. *
  33868. * @augments LightShadow
  33869. */
  33870. class SpotLightShadow extends LightShadow {
  33871. /**
  33872. * Constructs a new spot light shadow.
  33873. */
  33874. constructor() {
  33875. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33876. /**
  33877. * This flag can be used for type testing.
  33878. *
  33879. * @type {boolean}
  33880. * @readonly
  33881. * @default true
  33882. */
  33883. this.isSpotLightShadow = true;
  33884. /**
  33885. * Used to focus the shadow camera. The camera's field of view is set as a
  33886. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33887. *
  33888. * @type {number}
  33889. * @default 1
  33890. */
  33891. this.focus = 1;
  33892. /**
  33893. * Texture aspect ratio.
  33894. *
  33895. * @type {number}
  33896. * @default 1
  33897. */
  33898. this.aspect = 1;
  33899. }
  33900. updateMatrices( light ) {
  33901. const camera = this.camera;
  33902. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33903. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33904. const far = light.distance || camera.far;
  33905. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33906. camera.fov = fov;
  33907. camera.aspect = aspect;
  33908. camera.far = far;
  33909. camera.updateProjectionMatrix();
  33910. }
  33911. super.updateMatrices( light );
  33912. }
  33913. copy( source ) {
  33914. super.copy( source );
  33915. this.focus = source.focus;
  33916. return this;
  33917. }
  33918. }
  33919. /**
  33920. * This light gets emitted from a single point in one direction, along a cone
  33921. * that increases in size the further from the light it gets.
  33922. *
  33923. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33924. *
  33925. * ```js
  33926. * // white spotlight shining from the side, modulated by a texture
  33927. * const spotLight = new THREE.SpotLight( 0xffffff );
  33928. * spotLight.position.set( 100, 1000, 100 );
  33929. * spotLight.map = new THREE.TextureLoader().load( url );
  33930. *
  33931. * spotLight.castShadow = true;
  33932. * spotLight.shadow.mapSize.width = 1024;
  33933. * spotLight.shadow.mapSize.height = 1024;
  33934. * spotLight.shadow.camera.near = 500;
  33935. * spotLight.shadow.camera.far = 4000;
  33936. * spotLight.shadow.camera.fov = 30;s
  33937. * ```
  33938. *
  33939. * @augments Light
  33940. */
  33941. class SpotLight extends Light {
  33942. /**
  33943. * Constructs a new spot light.
  33944. *
  33945. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33946. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33947. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33948. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33949. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33950. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33951. */
  33952. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33953. super( color, intensity );
  33954. /**
  33955. * This flag can be used for type testing.
  33956. *
  33957. * @type {boolean}
  33958. * @readonly
  33959. * @default true
  33960. */
  33961. this.isSpotLight = true;
  33962. this.type = 'SpotLight';
  33963. this.position.copy( Object3D.DEFAULT_UP );
  33964. this.updateMatrix();
  33965. /**
  33966. * The spot light points from its position to the
  33967. * target's position.
  33968. *
  33969. * For the target's position to be changed to anything other
  33970. * than the default, it must be added to the scene.
  33971. *
  33972. * It is also possible to set the target to be another 3D object
  33973. * in the scene. The light will now track the target object.
  33974. *
  33975. * @type {Object3D}
  33976. */
  33977. this.target = new Object3D();
  33978. /**
  33979. * Maximum range of the light. `0` means no limit.
  33980. *
  33981. * @type {number}
  33982. * @default 0
  33983. */
  33984. this.distance = distance;
  33985. /**
  33986. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33987. *
  33988. * @type {number}
  33989. * @default Math.PI/3
  33990. */
  33991. this.angle = angle;
  33992. /**
  33993. * Percent of the spotlight cone that is attenuated due to penumbra.
  33994. * Value range is `[0,1]`.
  33995. *
  33996. * @type {number}
  33997. * @default 0
  33998. */
  33999. this.penumbra = penumbra;
  34000. /**
  34001. * The amount the light dims along the distance of the light. In context of
  34002. * physically-correct rendering the default value should not be changed.
  34003. *
  34004. * @type {number}
  34005. * @default 2
  34006. */
  34007. this.decay = decay;
  34008. /**
  34009. * A texture used to modulate the color of the light. The spot light
  34010. * color is mixed with the RGB value of this texture, with a ratio
  34011. * corresponding to its alpha value. The cookie-like masking effect is
  34012. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  34013. *
  34014. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  34015. *
  34016. * @type {?Texture}
  34017. * @default null
  34018. */
  34019. this.map = null;
  34020. /**
  34021. * This property holds the light's shadow configuration.
  34022. *
  34023. * @type {SpotLightShadow}
  34024. */
  34025. this.shadow = new SpotLightShadow();
  34026. }
  34027. /**
  34028. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34029. * Changing the power will also change the light's intensity.
  34030. *
  34031. * @type {number}
  34032. */
  34033. get power() {
  34034. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34035. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  34036. return this.intensity * Math.PI;
  34037. }
  34038. set power( power ) {
  34039. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34040. this.intensity = power / Math.PI;
  34041. }
  34042. dispose() {
  34043. super.dispose();
  34044. this.shadow.dispose();
  34045. }
  34046. copy( source, recursive ) {
  34047. super.copy( source, recursive );
  34048. this.distance = source.distance;
  34049. this.angle = source.angle;
  34050. this.penumbra = source.penumbra;
  34051. this.decay = source.decay;
  34052. this.target = source.target.clone();
  34053. this.map = source.map;
  34054. this.shadow = source.shadow.clone();
  34055. return this;
  34056. }
  34057. toJSON( meta ) {
  34058. const data = super.toJSON( meta );
  34059. data.object.distance = this.distance;
  34060. data.object.angle = this.angle;
  34061. data.object.decay = this.decay;
  34062. data.object.penumbra = this.penumbra;
  34063. data.object.target = this.target.uuid;
  34064. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  34065. data.object.shadow = this.shadow.toJSON();
  34066. return data;
  34067. }
  34068. }
  34069. /**
  34070. * Represents the shadow configuration of point lights.
  34071. *
  34072. * @augments LightShadow
  34073. */
  34074. class PointLightShadow extends LightShadow {
  34075. /**
  34076. * Constructs a new point light shadow.
  34077. */
  34078. constructor() {
  34079. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  34080. /**
  34081. * This flag can be used for type testing.
  34082. *
  34083. * @type {boolean}
  34084. * @readonly
  34085. * @default true
  34086. */
  34087. this.isPointLightShadow = true;
  34088. }
  34089. }
  34090. /**
  34091. * A light that gets emitted from a single point in all directions. A common
  34092. * use case for this is to replicate the light emitted from a bare
  34093. * lightbulb.
  34094. *
  34095. * This light can cast shadows - see the {@link PointLightShadow} for details.
  34096. *
  34097. * ```js
  34098. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  34099. * light.position.set( 50, 50, 50 );
  34100. * scene.add( light );
  34101. * ```
  34102. *
  34103. * @augments Light
  34104. */
  34105. class PointLight extends Light {
  34106. /**
  34107. * Constructs a new point light.
  34108. *
  34109. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34110. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  34111. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  34112. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  34113. */
  34114. constructor( color, intensity, distance = 0, decay = 2 ) {
  34115. super( color, intensity );
  34116. /**
  34117. * This flag can be used for type testing.
  34118. *
  34119. * @type {boolean}
  34120. * @readonly
  34121. * @default true
  34122. */
  34123. this.isPointLight = true;
  34124. this.type = 'PointLight';
  34125. /**
  34126. * When distance is zero, light will attenuate according to inverse-square
  34127. * law to infinite distance. When distance is non-zero, light will attenuate
  34128. * according to inverse-square law until near the distance cutoff, where it
  34129. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  34130. * physically correct.
  34131. *
  34132. * @type {number}
  34133. * @default 0
  34134. */
  34135. this.distance = distance;
  34136. /**
  34137. * The amount the light dims along the distance of the light. In context of
  34138. * physically-correct rendering the default value should not be changed.
  34139. *
  34140. * @type {number}
  34141. * @default 2
  34142. */
  34143. this.decay = decay;
  34144. /**
  34145. * This property holds the light's shadow configuration.
  34146. *
  34147. * @type {PointLightShadow}
  34148. */
  34149. this.shadow = new PointLightShadow();
  34150. }
  34151. /**
  34152. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34153. * Changing the power will also change the light's intensity.
  34154. *
  34155. * @type {number}
  34156. */
  34157. get power() {
  34158. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34159. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  34160. return this.intensity * 4 * Math.PI;
  34161. }
  34162. set power( power ) {
  34163. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34164. this.intensity = power / ( 4 * Math.PI );
  34165. }
  34166. dispose() {
  34167. super.dispose();
  34168. this.shadow.dispose();
  34169. }
  34170. copy( source, recursive ) {
  34171. super.copy( source, recursive );
  34172. this.distance = source.distance;
  34173. this.decay = source.decay;
  34174. this.shadow = source.shadow.clone();
  34175. return this;
  34176. }
  34177. toJSON( meta ) {
  34178. const data = super.toJSON( meta );
  34179. data.object.distance = this.distance;
  34180. data.object.decay = this.decay;
  34181. data.object.shadow = this.shadow.toJSON();
  34182. return data;
  34183. }
  34184. }
  34185. /**
  34186. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  34187. *
  34188. * In this projection mode, an object's size in the rendered image stays
  34189. * constant regardless of its distance from the camera. This can be useful
  34190. * for rendering 2D scenes and UI elements, amongst other things.
  34191. *
  34192. * ```js
  34193. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  34194. * scene.add( camera );
  34195. * ```
  34196. *
  34197. * @augments Camera
  34198. */
  34199. class OrthographicCamera extends Camera {
  34200. /**
  34201. * Constructs a new orthographic camera.
  34202. *
  34203. * @param {number} [left=-1] - The left plane of the camera's frustum.
  34204. * @param {number} [right=1] - The right plane of the camera's frustum.
  34205. * @param {number} [top=1] - The top plane of the camera's frustum.
  34206. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  34207. * @param {number} [near=0.1] - The camera's near plane.
  34208. * @param {number} [far=2000] - The camera's far plane.
  34209. */
  34210. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  34211. super();
  34212. /**
  34213. * This flag can be used for type testing.
  34214. *
  34215. * @type {boolean}
  34216. * @readonly
  34217. * @default true
  34218. */
  34219. this.isOrthographicCamera = true;
  34220. this.type = 'OrthographicCamera';
  34221. /**
  34222. * The zoom factor of the camera.
  34223. *
  34224. * @type {number}
  34225. * @default 1
  34226. */
  34227. this.zoom = 1;
  34228. /**
  34229. * Represents the frustum window specification. This property should not be edited
  34230. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34231. *
  34232. * @type {?Object}
  34233. * @default null
  34234. */
  34235. this.view = null;
  34236. /**
  34237. * The left plane of the camera's frustum.
  34238. *
  34239. * @type {number}
  34240. * @default -1
  34241. */
  34242. this.left = left;
  34243. /**
  34244. * The right plane of the camera's frustum.
  34245. *
  34246. * @type {number}
  34247. * @default 1
  34248. */
  34249. this.right = right;
  34250. /**
  34251. * The top plane of the camera's frustum.
  34252. *
  34253. * @type {number}
  34254. * @default 1
  34255. */
  34256. this.top = top;
  34257. /**
  34258. * The bottom plane of the camera's frustum.
  34259. *
  34260. * @type {number}
  34261. * @default -1
  34262. */
  34263. this.bottom = bottom;
  34264. /**
  34265. * The camera's near plane. The valid range is greater than `0`
  34266. * and less than the current value of {@link OrthographicCamera#far}.
  34267. *
  34268. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  34269. * valid value for an orthographic camera's near plane.
  34270. *
  34271. * @type {number}
  34272. * @default 0.1
  34273. */
  34274. this.near = near;
  34275. /**
  34276. * The camera's far plane. Must be greater than the
  34277. * current value of {@link OrthographicCamera#near}.
  34278. *
  34279. * @type {number}
  34280. * @default 2000
  34281. */
  34282. this.far = far;
  34283. this.updateProjectionMatrix();
  34284. }
  34285. copy( source, recursive ) {
  34286. super.copy( source, recursive );
  34287. this.left = source.left;
  34288. this.right = source.right;
  34289. this.top = source.top;
  34290. this.bottom = source.bottom;
  34291. this.near = source.near;
  34292. this.far = source.far;
  34293. this.zoom = source.zoom;
  34294. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34295. return this;
  34296. }
  34297. /**
  34298. * Sets an offset in a larger frustum. This is useful for multi-window or
  34299. * multi-monitor/multi-machine setups.
  34300. *
  34301. * @param {number} fullWidth - The full width of multiview setup.
  34302. * @param {number} fullHeight - The full height of multiview setup.
  34303. * @param {number} x - The horizontal offset of the subcamera.
  34304. * @param {number} y - The vertical offset of the subcamera.
  34305. * @param {number} width - The width of subcamera.
  34306. * @param {number} height - The height of subcamera.
  34307. * @see {@link PerspectiveCamera#setViewOffset}
  34308. */
  34309. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34310. if ( this.view === null ) {
  34311. this.view = {
  34312. enabled: true,
  34313. fullWidth: 1,
  34314. fullHeight: 1,
  34315. offsetX: 0,
  34316. offsetY: 0,
  34317. width: 1,
  34318. height: 1
  34319. };
  34320. }
  34321. this.view.enabled = true;
  34322. this.view.fullWidth = fullWidth;
  34323. this.view.fullHeight = fullHeight;
  34324. this.view.offsetX = x;
  34325. this.view.offsetY = y;
  34326. this.view.width = width;
  34327. this.view.height = height;
  34328. this.updateProjectionMatrix();
  34329. }
  34330. /**
  34331. * Removes the view offset from the projection matrix.
  34332. */
  34333. clearViewOffset() {
  34334. if ( this.view !== null ) {
  34335. this.view.enabled = false;
  34336. }
  34337. this.updateProjectionMatrix();
  34338. }
  34339. /**
  34340. * Updates the camera's projection matrix. Must be called after any change of
  34341. * camera properties.
  34342. */
  34343. updateProjectionMatrix() {
  34344. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34345. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34346. const cx = ( this.right + this.left ) / 2;
  34347. const cy = ( this.top + this.bottom ) / 2;
  34348. let left = cx - dx;
  34349. let right = cx + dx;
  34350. let top = cy + dy;
  34351. let bottom = cy - dy;
  34352. if ( this.view !== null && this.view.enabled ) {
  34353. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34354. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34355. left += scaleW * this.view.offsetX;
  34356. right = left + scaleW * this.view.width;
  34357. top -= scaleH * this.view.offsetY;
  34358. bottom = top - scaleH * this.view.height;
  34359. }
  34360. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34361. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34362. }
  34363. toJSON( meta ) {
  34364. const data = super.toJSON( meta );
  34365. data.object.zoom = this.zoom;
  34366. data.object.left = this.left;
  34367. data.object.right = this.right;
  34368. data.object.top = this.top;
  34369. data.object.bottom = this.bottom;
  34370. data.object.near = this.near;
  34371. data.object.far = this.far;
  34372. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34373. return data;
  34374. }
  34375. }
  34376. /**
  34377. * Represents the shadow configuration of directional lights.
  34378. *
  34379. * @augments LightShadow
  34380. */
  34381. class DirectionalLightShadow extends LightShadow {
  34382. /**
  34383. * Constructs a new directional light shadow.
  34384. */
  34385. constructor() {
  34386. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34387. /**
  34388. * This flag can be used for type testing.
  34389. *
  34390. * @type {boolean}
  34391. * @readonly
  34392. * @default true
  34393. */
  34394. this.isDirectionalLightShadow = true;
  34395. }
  34396. }
  34397. /**
  34398. * A light that gets emitted in a specific direction. This light will behave
  34399. * as though it is infinitely far away and the rays produced from it are all
  34400. * parallel. The common use case for this is to simulate daylight; the sun is
  34401. * far enough away that its position can be considered to be infinite, and
  34402. * all light rays coming from it are parallel.
  34403. *
  34404. * A common point of confusion for directional lights is that setting the
  34405. * rotation has no effect. This is because three.js's DirectionalLight is the
  34406. * equivalent to what is often called a 'Target Direct Light' in other
  34407. * applications.
  34408. *
  34409. * This means that its direction is calculated as pointing from the light's
  34410. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34411. * (as opposed to a 'Free Direct Light' that just has a rotation
  34412. * component).
  34413. *
  34414. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34415. *
  34416. * ```js
  34417. * // White directional light at half intensity shining from the top.
  34418. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34419. * scene.add( directionalLight );
  34420. * ```
  34421. *
  34422. * @augments Light
  34423. */
  34424. class DirectionalLight extends Light {
  34425. /**
  34426. * Constructs a new directional light.
  34427. *
  34428. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34429. * @param {number} [intensity=1] - The light's strength/intensity.
  34430. */
  34431. constructor( color, intensity ) {
  34432. super( color, intensity );
  34433. /**
  34434. * This flag can be used for type testing.
  34435. *
  34436. * @type {boolean}
  34437. * @readonly
  34438. * @default true
  34439. */
  34440. this.isDirectionalLight = true;
  34441. this.type = 'DirectionalLight';
  34442. this.position.copy( Object3D.DEFAULT_UP );
  34443. this.updateMatrix();
  34444. /**
  34445. * The directional light points from its position to the
  34446. * target's position.
  34447. *
  34448. * For the target's position to be changed to anything other
  34449. * than the default, it must be added to the scene.
  34450. *
  34451. * It is also possible to set the target to be another 3D object
  34452. * in the scene. The light will now track the target object.
  34453. *
  34454. * @type {Object3D}
  34455. */
  34456. this.target = new Object3D();
  34457. /**
  34458. * This property holds the light's shadow configuration.
  34459. *
  34460. * @type {DirectionalLightShadow}
  34461. */
  34462. this.shadow = new DirectionalLightShadow();
  34463. }
  34464. dispose() {
  34465. super.dispose();
  34466. this.shadow.dispose();
  34467. }
  34468. copy( source ) {
  34469. super.copy( source );
  34470. this.target = source.target.clone();
  34471. this.shadow = source.shadow.clone();
  34472. return this;
  34473. }
  34474. toJSON( meta ) {
  34475. const data = super.toJSON( meta );
  34476. data.object.shadow = this.shadow.toJSON();
  34477. data.object.target = this.target.uuid;
  34478. return data;
  34479. }
  34480. }
  34481. /**
  34482. * This light globally illuminates all objects in the scene equally.
  34483. *
  34484. * It cannot be used to cast shadows as it does not have a direction.
  34485. *
  34486. * ```js
  34487. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34488. * scene.add( light );
  34489. * ```
  34490. *
  34491. * @augments Light
  34492. */
  34493. class AmbientLight extends Light {
  34494. /**
  34495. * Constructs a new ambient light.
  34496. *
  34497. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34498. * @param {number} [intensity=1] - The light's strength/intensity.
  34499. */
  34500. constructor( color, intensity ) {
  34501. super( color, intensity );
  34502. /**
  34503. * This flag can be used for type testing.
  34504. *
  34505. * @type {boolean}
  34506. * @readonly
  34507. * @default true
  34508. */
  34509. this.isAmbientLight = true;
  34510. this.type = 'AmbientLight';
  34511. }
  34512. }
  34513. /**
  34514. * This class emits light uniformly across the face a rectangular plane.
  34515. * This light type can be used to simulate light sources such as bright
  34516. * windows or strip lighting.
  34517. *
  34518. * Important Notes:
  34519. *
  34520. * - There is no shadow support.
  34521. * - Only PBR materials are supported.
  34522. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34523. * into your app and init the uniforms/textures.
  34524. *
  34525. * ```js
  34526. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34527. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34528. *
  34529. * const intensity = 1; const width = 10; const height = 10;
  34530. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34531. * rectLight.position.set( 5, 5, 0 );
  34532. * rectLight.lookAt( 0, 0, 0 );
  34533. * scene.add( rectLight )
  34534. * ```
  34535. *
  34536. * @augments Light
  34537. */
  34538. class RectAreaLight extends Light {
  34539. /**
  34540. * Constructs a new area light.
  34541. *
  34542. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34543. * @param {number} [intensity=1] - The light's strength/intensity.
  34544. * @param {number} [width=10] - The width of the light.
  34545. * @param {number} [height=10] - The height of the light.
  34546. */
  34547. constructor( color, intensity, width = 10, height = 10 ) {
  34548. super( color, intensity );
  34549. /**
  34550. * This flag can be used for type testing.
  34551. *
  34552. * @type {boolean}
  34553. * @readonly
  34554. * @default true
  34555. */
  34556. this.isRectAreaLight = true;
  34557. this.type = 'RectAreaLight';
  34558. /**
  34559. * The width of the light.
  34560. *
  34561. * @type {number}
  34562. * @default 10
  34563. */
  34564. this.width = width;
  34565. /**
  34566. * The height of the light.
  34567. *
  34568. * @type {number}
  34569. * @default 10
  34570. */
  34571. this.height = height;
  34572. }
  34573. /**
  34574. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34575. * Changing the power will also change the light's intensity.
  34576. *
  34577. * @type {number}
  34578. */
  34579. get power() {
  34580. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34581. return this.intensity * this.width * this.height * Math.PI;
  34582. }
  34583. set power( power ) {
  34584. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34585. this.intensity = power / ( this.width * this.height * Math.PI );
  34586. }
  34587. copy( source ) {
  34588. super.copy( source );
  34589. this.width = source.width;
  34590. this.height = source.height;
  34591. return this;
  34592. }
  34593. toJSON( meta ) {
  34594. const data = super.toJSON( meta );
  34595. data.object.width = this.width;
  34596. data.object.height = this.height;
  34597. return data;
  34598. }
  34599. }
  34600. /**
  34601. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34602. * to encode lighting information.
  34603. *
  34604. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34605. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34606. */
  34607. class SphericalHarmonics3 {
  34608. /**
  34609. * Constructs a new spherical harmonics.
  34610. */
  34611. constructor() {
  34612. /**
  34613. * This flag can be used for type testing.
  34614. *
  34615. * @type {boolean}
  34616. * @readonly
  34617. * @default true
  34618. */
  34619. this.isSphericalHarmonics3 = true;
  34620. /**
  34621. * An array holding the (9) SH coefficients.
  34622. *
  34623. * @type {Array<Vector3>}
  34624. */
  34625. this.coefficients = [];
  34626. for ( let i = 0; i < 9; i ++ ) {
  34627. this.coefficients.push( new Vector3() );
  34628. }
  34629. }
  34630. /**
  34631. * Sets the given SH coefficients to this instance by copying
  34632. * the values.
  34633. *
  34634. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34635. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34636. */
  34637. set( coefficients ) {
  34638. for ( let i = 0; i < 9; i ++ ) {
  34639. this.coefficients[ i ].copy( coefficients[ i ] );
  34640. }
  34641. return this;
  34642. }
  34643. /**
  34644. * Sets all SH coefficients to `0`.
  34645. *
  34646. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34647. */
  34648. zero() {
  34649. for ( let i = 0; i < 9; i ++ ) {
  34650. this.coefficients[ i ].set( 0, 0, 0 );
  34651. }
  34652. return this;
  34653. }
  34654. /**
  34655. * Returns the radiance in the direction of the given normal.
  34656. *
  34657. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34658. * @param {Vector3} target - The target vector that is used to store the method's result.
  34659. * @return {Vector3} The radiance.
  34660. */
  34661. getAt( normal, target ) {
  34662. // normal is assumed to be unit length
  34663. const x = normal.x, y = normal.y, z = normal.z;
  34664. const coeff = this.coefficients;
  34665. // band 0
  34666. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34667. // band 1
  34668. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34669. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34670. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34671. // band 2
  34672. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34673. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34674. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34675. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34676. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34677. return target;
  34678. }
  34679. /**
  34680. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34681. * direction of the given normal.
  34682. *
  34683. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34684. * @param {Vector3} target - The target vector that is used to store the method's result.
  34685. * @return {Vector3} The irradiance.
  34686. */
  34687. getIrradianceAt( normal, target ) {
  34688. // normal is assumed to be unit length
  34689. const x = normal.x, y = normal.y, z = normal.z;
  34690. const coeff = this.coefficients;
  34691. // band 0
  34692. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34693. // band 1
  34694. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34695. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34696. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34697. // band 2
  34698. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34699. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34700. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34701. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34702. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34703. return target;
  34704. }
  34705. /**
  34706. * Adds the given SH to this instance.
  34707. *
  34708. * @param {SphericalHarmonics3} sh - The SH to add.
  34709. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34710. */
  34711. add( sh ) {
  34712. for ( let i = 0; i < 9; i ++ ) {
  34713. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34714. }
  34715. return this;
  34716. }
  34717. /**
  34718. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34719. * {@link SphericalHarmonics3#scale} at once.
  34720. *
  34721. * @param {SphericalHarmonics3} sh - The SH to add.
  34722. * @param {number} s - The scale factor.
  34723. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34724. */
  34725. addScaledSH( sh, s ) {
  34726. for ( let i = 0; i < 9; i ++ ) {
  34727. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34728. }
  34729. return this;
  34730. }
  34731. /**
  34732. * Scales this SH by the given scale factor.
  34733. *
  34734. * @param {number} s - The scale factor.
  34735. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34736. */
  34737. scale( s ) {
  34738. for ( let i = 0; i < 9; i ++ ) {
  34739. this.coefficients[ i ].multiplyScalar( s );
  34740. }
  34741. return this;
  34742. }
  34743. /**
  34744. * Linear interpolates between the given SH and this instance by the given
  34745. * alpha factor.
  34746. *
  34747. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34748. * @param {number} alpha - The alpha factor.
  34749. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34750. */
  34751. lerp( sh, alpha ) {
  34752. for ( let i = 0; i < 9; i ++ ) {
  34753. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34754. }
  34755. return this;
  34756. }
  34757. /**
  34758. * Returns `true` if this spherical harmonics is equal with the given one.
  34759. *
  34760. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34761. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34762. */
  34763. equals( sh ) {
  34764. for ( let i = 0; i < 9; i ++ ) {
  34765. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34766. return false;
  34767. }
  34768. }
  34769. return true;
  34770. }
  34771. /**
  34772. * Copies the values of the given spherical harmonics to this instance.
  34773. *
  34774. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34775. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34776. */
  34777. copy( sh ) {
  34778. return this.set( sh.coefficients );
  34779. }
  34780. /**
  34781. * Returns a new spherical harmonics with copied values from this instance.
  34782. *
  34783. * @return {SphericalHarmonics3} A clone of this instance.
  34784. */
  34785. clone() {
  34786. return new this.constructor().copy( this );
  34787. }
  34788. /**
  34789. * Sets the SH coefficients of this instance from the given array.
  34790. *
  34791. * @param {Array<number>} array - An array holding the SH coefficients.
  34792. * @param {number} [offset=0] - The array offset where to start copying.
  34793. * @return {SphericalHarmonics3} A clone of this instance.
  34794. */
  34795. fromArray( array, offset = 0 ) {
  34796. const coefficients = this.coefficients;
  34797. for ( let i = 0; i < 9; i ++ ) {
  34798. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34799. }
  34800. return this;
  34801. }
  34802. /**
  34803. * Returns an array with the SH coefficients, or copies them into the provided
  34804. * array. The coefficients are represented as numbers.
  34805. *
  34806. * @param {Array<number>} [array=[]] - The target array.
  34807. * @param {number} [offset=0] - The array offset where to start copying.
  34808. * @return {Array<number>} An array with flat SH coefficients.
  34809. */
  34810. toArray( array = [], offset = 0 ) {
  34811. const coefficients = this.coefficients;
  34812. for ( let i = 0; i < 9; i ++ ) {
  34813. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34814. }
  34815. return array;
  34816. }
  34817. /**
  34818. * Computes the SH basis for the given normal vector.
  34819. *
  34820. * @param {Vector3} normal - The normal.
  34821. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34822. */
  34823. static getBasisAt( normal, shBasis ) {
  34824. // normal is assumed to be unit length
  34825. const x = normal.x, y = normal.y, z = normal.z;
  34826. // band 0
  34827. shBasis[ 0 ] = 0.282095;
  34828. // band 1
  34829. shBasis[ 1 ] = 0.488603 * y;
  34830. shBasis[ 2 ] = 0.488603 * z;
  34831. shBasis[ 3 ] = 0.488603 * x;
  34832. // band 2
  34833. shBasis[ 4 ] = 1.092548 * x * y;
  34834. shBasis[ 5 ] = 1.092548 * y * z;
  34835. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34836. shBasis[ 7 ] = 1.092548 * x * z;
  34837. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34838. }
  34839. }
  34840. /**
  34841. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34842. * classical light sources (e.g. directional, point or spot lights), light
  34843. * probes do not emit light. Instead they store information about light
  34844. * passing through 3D space. During rendering, the light that hits a 3D
  34845. * object is approximated by using the data from the light probe.
  34846. *
  34847. * Light probes are usually created from (radiance) environment maps. The
  34848. * class {@link LightProbeGenerator} can be used to create light probes from
  34849. * cube textures or render targets. However, light estimation data could also
  34850. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34851. * augmented reality content that reacts to real world lighting.
  34852. *
  34853. * The current probe implementation in three.js supports so-called diffuse
  34854. * light probes. This type of light probe is functionally equivalent to an
  34855. * irradiance environment map.
  34856. *
  34857. * @augments Light
  34858. */
  34859. class LightProbe extends Light {
  34860. /**
  34861. * Constructs a new light probe.
  34862. *
  34863. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34864. * @param {number} [intensity=1] - The light's strength/intensity.
  34865. */
  34866. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34867. super( undefined, intensity );
  34868. /**
  34869. * This flag can be used for type testing.
  34870. *
  34871. * @type {boolean}
  34872. * @readonly
  34873. * @default true
  34874. */
  34875. this.isLightProbe = true;
  34876. /**
  34877. * A light probe uses spherical harmonics to encode lighting information.
  34878. *
  34879. * @type {SphericalHarmonics3}
  34880. */
  34881. this.sh = sh;
  34882. }
  34883. copy( source ) {
  34884. super.copy( source );
  34885. this.sh.copy( source.sh );
  34886. return this;
  34887. }
  34888. toJSON( meta ) {
  34889. const data = super.toJSON( meta );
  34890. data.object.sh = this.sh.toArray();
  34891. return data;
  34892. }
  34893. }
  34894. /**
  34895. * Class for loading materials. The files are internally
  34896. * loaded via {@link FileLoader}.
  34897. *
  34898. * ```js
  34899. * const loader = new THREE.MaterialLoader();
  34900. * const material = await loader.loadAsync( 'material.json' );
  34901. * ```
  34902. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34903. *
  34904. * @augments Loader
  34905. */
  34906. class MaterialLoader extends Loader {
  34907. /**
  34908. * Constructs a new material loader.
  34909. *
  34910. * @param {LoadingManager} [manager] - The loading manager.
  34911. */
  34912. constructor( manager ) {
  34913. super( manager );
  34914. /**
  34915. * A dictionary holding textures used by the material.
  34916. *
  34917. * @type {Object<string,Texture>}
  34918. */
  34919. this.textures = {};
  34920. }
  34921. /**
  34922. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34923. *
  34924. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34925. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34926. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34927. * @param {onErrorCallback} onError - Executed when errors occur.
  34928. */
  34929. load( url, onLoad, onProgress, onError ) {
  34930. const scope = this;
  34931. const loader = new FileLoader( scope.manager );
  34932. loader.setPath( scope.path );
  34933. loader.setRequestHeader( scope.requestHeader );
  34934. loader.setWithCredentials( scope.withCredentials );
  34935. loader.load( url, function ( text ) {
  34936. try {
  34937. onLoad( scope.parse( JSON.parse( text ) ) );
  34938. } catch ( e ) {
  34939. if ( onError ) {
  34940. onError( e );
  34941. } else {
  34942. error( e );
  34943. }
  34944. scope.manager.itemError( url );
  34945. }
  34946. }, onProgress, onError );
  34947. }
  34948. /**
  34949. * Parses the given JSON object and returns a material.
  34950. *
  34951. * @param {Object} json - The serialized material.
  34952. * @return {Material} The parsed material.
  34953. */
  34954. parse( json ) {
  34955. const textures = this.textures;
  34956. function getTexture( name ) {
  34957. if ( textures[ name ] === undefined ) {
  34958. warn( 'MaterialLoader: Undefined texture', name );
  34959. }
  34960. return textures[ name ];
  34961. }
  34962. const material = this.createMaterialFromType( json.type );
  34963. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34964. if ( json.name !== undefined ) material.name = json.name;
  34965. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34966. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34967. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34968. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34969. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34970. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34971. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34972. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34973. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34974. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34975. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34976. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34977. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34978. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34979. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34980. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34981. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34982. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34983. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34984. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34985. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34986. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34987. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34988. if ( json.fog !== undefined ) material.fog = json.fog;
  34989. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34990. if ( json.blending !== undefined ) material.blending = json.blending;
  34991. if ( json.combine !== undefined ) material.combine = json.combine;
  34992. if ( json.side !== undefined ) material.side = json.side;
  34993. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34994. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34995. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34996. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34997. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34998. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34999. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  35000. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  35001. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  35002. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  35003. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  35004. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  35005. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  35006. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  35007. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  35008. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  35009. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  35010. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  35011. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  35012. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  35013. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  35014. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  35015. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  35016. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  35017. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  35018. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  35019. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  35020. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  35021. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  35022. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  35023. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  35024. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  35025. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  35026. if ( json.scale !== undefined ) material.scale = json.scale;
  35027. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  35028. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  35029. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  35030. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  35031. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  35032. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  35033. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  35034. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  35035. if ( json.visible !== undefined ) material.visible = json.visible;
  35036. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  35037. if ( json.userData !== undefined ) material.userData = json.userData;
  35038. if ( json.vertexColors !== undefined ) {
  35039. if ( typeof json.vertexColors === 'number' ) {
  35040. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  35041. } else {
  35042. material.vertexColors = json.vertexColors;
  35043. }
  35044. }
  35045. // Shader Material
  35046. if ( json.uniforms !== undefined ) {
  35047. for ( const name in json.uniforms ) {
  35048. const uniform = json.uniforms[ name ];
  35049. material.uniforms[ name ] = {};
  35050. switch ( uniform.type ) {
  35051. case 't':
  35052. material.uniforms[ name ].value = getTexture( uniform.value );
  35053. break;
  35054. case 'c':
  35055. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  35056. break;
  35057. case 'v2':
  35058. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  35059. break;
  35060. case 'v3':
  35061. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  35062. break;
  35063. case 'v4':
  35064. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  35065. break;
  35066. case 'm3':
  35067. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  35068. break;
  35069. case 'm4':
  35070. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  35071. break;
  35072. default:
  35073. material.uniforms[ name ].value = uniform.value;
  35074. }
  35075. }
  35076. }
  35077. if ( json.defines !== undefined ) material.defines = json.defines;
  35078. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  35079. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  35080. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  35081. if ( json.extensions !== undefined ) {
  35082. for ( const key in json.extensions ) {
  35083. material.extensions[ key ] = json.extensions[ key ];
  35084. }
  35085. }
  35086. if ( json.lights !== undefined ) material.lights = json.lights;
  35087. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  35088. // for PointsMaterial
  35089. if ( json.size !== undefined ) material.size = json.size;
  35090. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  35091. // maps
  35092. if ( json.map !== undefined ) material.map = getTexture( json.map );
  35093. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  35094. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  35095. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  35096. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  35097. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  35098. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  35099. if ( json.normalScale !== undefined ) {
  35100. let normalScale = json.normalScale;
  35101. if ( Array.isArray( normalScale ) === false ) {
  35102. // Blender exporter used to export a scalar. See #7459
  35103. normalScale = [ normalScale, normalScale ];
  35104. }
  35105. material.normalScale = new Vector2().fromArray( normalScale );
  35106. }
  35107. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  35108. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  35109. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  35110. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  35111. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  35112. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  35113. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  35114. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  35115. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  35116. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  35117. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  35118. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  35119. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  35120. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  35121. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  35122. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  35123. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  35124. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  35125. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  35126. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  35127. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  35128. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  35129. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  35130. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  35131. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  35132. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  35133. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  35134. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  35135. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  35136. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  35137. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  35138. return material;
  35139. }
  35140. /**
  35141. * Textures are not embedded in the material JSON so they have
  35142. * to be injected before the loading process starts.
  35143. *
  35144. * @param {Object} value - A dictionary holding textures for material properties.
  35145. * @return {MaterialLoader} A reference to this material loader.
  35146. */
  35147. setTextures( value ) {
  35148. this.textures = value;
  35149. return this;
  35150. }
  35151. /**
  35152. * Creates a material for the given type.
  35153. *
  35154. * @param {string} type - The material type.
  35155. * @return {Material} The new material.
  35156. */
  35157. createMaterialFromType( type ) {
  35158. return MaterialLoader.createMaterialFromType( type );
  35159. }
  35160. /**
  35161. * Creates a material for the given type.
  35162. *
  35163. * @static
  35164. * @param {string} type - The material type.
  35165. * @return {Material} The new material.
  35166. */
  35167. static createMaterialFromType( type ) {
  35168. const materialLib = {
  35169. ShadowMaterial,
  35170. SpriteMaterial,
  35171. RawShaderMaterial,
  35172. ShaderMaterial,
  35173. PointsMaterial,
  35174. MeshPhysicalMaterial,
  35175. MeshStandardMaterial,
  35176. MeshPhongMaterial,
  35177. MeshToonMaterial,
  35178. MeshNormalMaterial,
  35179. MeshLambertMaterial,
  35180. MeshDepthMaterial,
  35181. MeshDistanceMaterial,
  35182. MeshBasicMaterial,
  35183. MeshMatcapMaterial,
  35184. LineDashedMaterial,
  35185. LineBasicMaterial,
  35186. Material
  35187. };
  35188. return new materialLib[ type ]();
  35189. }
  35190. }
  35191. /**
  35192. * A class with loader utility functions.
  35193. */
  35194. class LoaderUtils {
  35195. /**
  35196. * Extracts the base URL from the given URL.
  35197. *
  35198. * @param {string} url -The URL to extract the base URL from.
  35199. * @return {string} The extracted base URL.
  35200. */
  35201. static extractUrlBase( url ) {
  35202. const index = url.lastIndexOf( '/' );
  35203. if ( index === -1 ) return './';
  35204. return url.slice( 0, index + 1 );
  35205. }
  35206. /**
  35207. * Resolves relative URLs against the given path. Absolute paths, data urls,
  35208. * and blob URLs will be returned as is. Invalid URLs will return an empty
  35209. * string.
  35210. *
  35211. * @param {string} url -The URL to resolve.
  35212. * @param {string} path - The base path for relative URLs to be resolved against.
  35213. * @return {string} The resolved URL.
  35214. */
  35215. static resolveURL( url, path ) {
  35216. // Invalid URL
  35217. if ( typeof url !== 'string' || url === '' ) return '';
  35218. // Host Relative URL
  35219. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  35220. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  35221. }
  35222. // Absolute URL http://,https://,//
  35223. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35224. // Data URI
  35225. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35226. // Blob URL
  35227. if ( /^blob:.*$/i.test( url ) ) return url;
  35228. // Relative URL
  35229. return path + url;
  35230. }
  35231. }
  35232. /**
  35233. * An instanced version of a geometry.
  35234. */
  35235. class InstancedBufferGeometry extends BufferGeometry {
  35236. /**
  35237. * Constructs a new instanced buffer geometry.
  35238. */
  35239. constructor() {
  35240. super();
  35241. /**
  35242. * This flag can be used for type testing.
  35243. *
  35244. * @type {boolean}
  35245. * @readonly
  35246. * @default true
  35247. */
  35248. this.isInstancedBufferGeometry = true;
  35249. this.type = 'InstancedBufferGeometry';
  35250. /**
  35251. * The instance count.
  35252. *
  35253. * @type {number}
  35254. * @default Infinity
  35255. */
  35256. this.instanceCount = Infinity;
  35257. }
  35258. copy( source ) {
  35259. super.copy( source );
  35260. this.instanceCount = source.instanceCount;
  35261. return this;
  35262. }
  35263. toJSON() {
  35264. const data = super.toJSON();
  35265. data.instanceCount = this.instanceCount;
  35266. data.isInstancedBufferGeometry = true;
  35267. return data;
  35268. }
  35269. }
  35270. /**
  35271. * Class for loading geometries. The files are internally
  35272. * loaded via {@link FileLoader}.
  35273. *
  35274. * ```js
  35275. * const loader = new THREE.BufferGeometryLoader();
  35276. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  35277. *
  35278. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  35279. * const object = new THREE.Mesh( geometry, material );
  35280. * scene.add( object );
  35281. * ```
  35282. *
  35283. * @augments Loader
  35284. */
  35285. class BufferGeometryLoader extends Loader {
  35286. /**
  35287. * Constructs a new geometry loader.
  35288. *
  35289. * @param {LoadingManager} [manager] - The loading manager.
  35290. */
  35291. constructor( manager ) {
  35292. super( manager );
  35293. }
  35294. /**
  35295. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  35296. *
  35297. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35298. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  35299. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35300. * @param {onErrorCallback} onError - Executed when errors occur.
  35301. */
  35302. load( url, onLoad, onProgress, onError ) {
  35303. const scope = this;
  35304. const loader = new FileLoader( scope.manager );
  35305. loader.setPath( scope.path );
  35306. loader.setRequestHeader( scope.requestHeader );
  35307. loader.setWithCredentials( scope.withCredentials );
  35308. loader.load( url, function ( text ) {
  35309. try {
  35310. onLoad( scope.parse( JSON.parse( text ) ) );
  35311. } catch ( e ) {
  35312. if ( onError ) {
  35313. onError( e );
  35314. } else {
  35315. error( e );
  35316. }
  35317. scope.manager.itemError( url );
  35318. }
  35319. }, onProgress, onError );
  35320. }
  35321. /**
  35322. * Parses the given JSON object and returns a geometry.
  35323. *
  35324. * @param {Object} json - The serialized geometry.
  35325. * @return {BufferGeometry} The parsed geometry.
  35326. */
  35327. parse( json ) {
  35328. const interleavedBufferMap = {};
  35329. const arrayBufferMap = {};
  35330. function getInterleavedBuffer( json, uuid ) {
  35331. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  35332. const interleavedBuffers = json.interleavedBuffers;
  35333. const interleavedBuffer = interleavedBuffers[ uuid ];
  35334. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  35335. const array = getTypedArray( interleavedBuffer.type, buffer );
  35336. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  35337. ib.uuid = interleavedBuffer.uuid;
  35338. interleavedBufferMap[ uuid ] = ib;
  35339. return ib;
  35340. }
  35341. function getArrayBuffer( json, uuid ) {
  35342. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  35343. const arrayBuffers = json.arrayBuffers;
  35344. const arrayBuffer = arrayBuffers[ uuid ];
  35345. const ab = new Uint32Array( arrayBuffer ).buffer;
  35346. arrayBufferMap[ uuid ] = ab;
  35347. return ab;
  35348. }
  35349. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35350. const index = json.data.index;
  35351. if ( index !== undefined ) {
  35352. const typedArray = getTypedArray( index.type, index.array );
  35353. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35354. }
  35355. const attributes = json.data.attributes;
  35356. for ( const key in attributes ) {
  35357. const attribute = attributes[ key ];
  35358. let bufferAttribute;
  35359. if ( attribute.isInterleavedBufferAttribute ) {
  35360. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35361. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35362. } else {
  35363. const typedArray = getTypedArray( attribute.type, attribute.array );
  35364. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35365. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35366. }
  35367. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35368. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35369. geometry.setAttribute( key, bufferAttribute );
  35370. }
  35371. const morphAttributes = json.data.morphAttributes;
  35372. if ( morphAttributes ) {
  35373. for ( const key in morphAttributes ) {
  35374. const attributeArray = morphAttributes[ key ];
  35375. const array = [];
  35376. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35377. const attribute = attributeArray[ i ];
  35378. let bufferAttribute;
  35379. if ( attribute.isInterleavedBufferAttribute ) {
  35380. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35381. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35382. } else {
  35383. const typedArray = getTypedArray( attribute.type, attribute.array );
  35384. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35385. }
  35386. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35387. array.push( bufferAttribute );
  35388. }
  35389. geometry.morphAttributes[ key ] = array;
  35390. }
  35391. }
  35392. const morphTargetsRelative = json.data.morphTargetsRelative;
  35393. if ( morphTargetsRelative ) {
  35394. geometry.morphTargetsRelative = true;
  35395. }
  35396. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35397. if ( groups !== undefined ) {
  35398. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35399. const group = groups[ i ];
  35400. geometry.addGroup( group.start, group.count, group.materialIndex );
  35401. }
  35402. }
  35403. const boundingSphere = json.data.boundingSphere;
  35404. if ( boundingSphere !== undefined ) {
  35405. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35406. }
  35407. if ( json.name ) geometry.name = json.name;
  35408. if ( json.userData ) geometry.userData = json.userData;
  35409. return geometry;
  35410. }
  35411. }
  35412. /**
  35413. * 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).
  35414. * The files are internally loaded via {@link FileLoader}.
  35415. *
  35416. * ```js
  35417. * const loader = new THREE.ObjectLoader();
  35418. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35419. * scene.add( obj );
  35420. *
  35421. * // Alternatively, to parse a previously loaded JSON structure
  35422. * const object = await loader.parseAsync( a_json_object );
  35423. * scene.add( object );
  35424. * ```
  35425. *
  35426. * @augments Loader
  35427. */
  35428. class ObjectLoader extends Loader {
  35429. /**
  35430. * Constructs a new object loader.
  35431. *
  35432. * @param {LoadingManager} [manager] - The loading manager.
  35433. */
  35434. constructor( manager ) {
  35435. super( manager );
  35436. }
  35437. /**
  35438. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35439. *
  35440. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35441. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35442. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35443. * @param {onErrorCallback} onError - Executed when errors occur.
  35444. */
  35445. load( url, onLoad, onProgress, onError ) {
  35446. const scope = this;
  35447. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35448. this.resourcePath = this.resourcePath || path;
  35449. const loader = new FileLoader( this.manager );
  35450. loader.setPath( this.path );
  35451. loader.setRequestHeader( this.requestHeader );
  35452. loader.setWithCredentials( this.withCredentials );
  35453. loader.load( url, function ( text ) {
  35454. let json = null;
  35455. try {
  35456. json = JSON.parse( text );
  35457. } catch ( error ) {
  35458. if ( onError !== undefined ) onError( error );
  35459. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  35460. return;
  35461. }
  35462. const metadata = json.metadata;
  35463. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35464. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35465. error( 'ObjectLoader: Can\'t load ' + url );
  35466. return;
  35467. }
  35468. scope.parse( json, onLoad );
  35469. }, onProgress, onError );
  35470. }
  35471. /**
  35472. * Async version of {@link ObjectLoader#load}.
  35473. *
  35474. * @async
  35475. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35476. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35477. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35478. */
  35479. async loadAsync( url, onProgress ) {
  35480. const scope = this;
  35481. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35482. this.resourcePath = this.resourcePath || path;
  35483. const loader = new FileLoader( this.manager );
  35484. loader.setPath( this.path );
  35485. loader.setRequestHeader( this.requestHeader );
  35486. loader.setWithCredentials( this.withCredentials );
  35487. const text = await loader.loadAsync( url, onProgress );
  35488. const json = JSON.parse( text );
  35489. const metadata = json.metadata;
  35490. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35491. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35492. }
  35493. return await scope.parseAsync( json );
  35494. }
  35495. /**
  35496. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35497. * but can also be used directly to parse a previously loaded JSON structure.
  35498. *
  35499. * @param {Object} json - The serialized 3D object.
  35500. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35501. * @return {Object3D} The parsed 3D object.
  35502. */
  35503. parse( json, onLoad ) {
  35504. const animations = this.parseAnimations( json.animations );
  35505. const shapes = this.parseShapes( json.shapes );
  35506. const geometries = this.parseGeometries( json.geometries, shapes );
  35507. const images = this.parseImages( json.images, function () {
  35508. if ( onLoad !== undefined ) onLoad( object );
  35509. } );
  35510. const textures = this.parseTextures( json.textures, images );
  35511. const materials = this.parseMaterials( json.materials, textures );
  35512. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35513. const skeletons = this.parseSkeletons( json.skeletons, object );
  35514. this.bindSkeletons( object, skeletons );
  35515. this.bindLightTargets( object );
  35516. //
  35517. if ( onLoad !== undefined ) {
  35518. let hasImages = false;
  35519. for ( const uuid in images ) {
  35520. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35521. hasImages = true;
  35522. break;
  35523. }
  35524. }
  35525. if ( hasImages === false ) onLoad( object );
  35526. }
  35527. return object;
  35528. }
  35529. /**
  35530. * Async version of {@link ObjectLoader#parse}.
  35531. *
  35532. * @param {Object} json - The serialized 3D object.
  35533. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35534. */
  35535. async parseAsync( json ) {
  35536. const animations = this.parseAnimations( json.animations );
  35537. const shapes = this.parseShapes( json.shapes );
  35538. const geometries = this.parseGeometries( json.geometries, shapes );
  35539. const images = await this.parseImagesAsync( json.images );
  35540. const textures = this.parseTextures( json.textures, images );
  35541. const materials = this.parseMaterials( json.materials, textures );
  35542. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35543. const skeletons = this.parseSkeletons( json.skeletons, object );
  35544. this.bindSkeletons( object, skeletons );
  35545. this.bindLightTargets( object );
  35546. return object;
  35547. }
  35548. // internals
  35549. parseShapes( json ) {
  35550. const shapes = {};
  35551. if ( json !== undefined ) {
  35552. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35553. const shape = new Shape().fromJSON( json[ i ] );
  35554. shapes[ shape.uuid ] = shape;
  35555. }
  35556. }
  35557. return shapes;
  35558. }
  35559. parseSkeletons( json, object ) {
  35560. const skeletons = {};
  35561. const bones = {};
  35562. // generate bone lookup table
  35563. object.traverse( function ( child ) {
  35564. if ( child.isBone ) bones[ child.uuid ] = child;
  35565. } );
  35566. // create skeletons
  35567. if ( json !== undefined ) {
  35568. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35569. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35570. skeletons[ skeleton.uuid ] = skeleton;
  35571. }
  35572. }
  35573. return skeletons;
  35574. }
  35575. parseGeometries( json, shapes ) {
  35576. const geometries = {};
  35577. if ( json !== undefined ) {
  35578. const bufferGeometryLoader = new BufferGeometryLoader();
  35579. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35580. let geometry;
  35581. const data = json[ i ];
  35582. switch ( data.type ) {
  35583. case 'BufferGeometry':
  35584. case 'InstancedBufferGeometry':
  35585. geometry = bufferGeometryLoader.parse( data );
  35586. break;
  35587. default:
  35588. if ( data.type in Geometries ) {
  35589. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35590. } else {
  35591. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35592. }
  35593. }
  35594. geometry.uuid = data.uuid;
  35595. if ( data.name !== undefined ) geometry.name = data.name;
  35596. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35597. geometries[ data.uuid ] = geometry;
  35598. }
  35599. }
  35600. return geometries;
  35601. }
  35602. parseMaterials( json, textures ) {
  35603. const cache = {}; // MultiMaterial
  35604. const materials = {};
  35605. if ( json !== undefined ) {
  35606. const loader = new MaterialLoader();
  35607. loader.setTextures( textures );
  35608. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35609. const data = json[ i ];
  35610. if ( cache[ data.uuid ] === undefined ) {
  35611. cache[ data.uuid ] = loader.parse( data );
  35612. }
  35613. materials[ data.uuid ] = cache[ data.uuid ];
  35614. }
  35615. }
  35616. return materials;
  35617. }
  35618. parseAnimations( json ) {
  35619. const animations = {};
  35620. if ( json !== undefined ) {
  35621. for ( let i = 0; i < json.length; i ++ ) {
  35622. const data = json[ i ];
  35623. const clip = AnimationClip.parse( data );
  35624. animations[ clip.uuid ] = clip;
  35625. }
  35626. }
  35627. return animations;
  35628. }
  35629. parseImages( json, onLoad ) {
  35630. const scope = this;
  35631. const images = {};
  35632. let loader;
  35633. function loadImage( url ) {
  35634. scope.manager.itemStart( url );
  35635. return loader.load( url, function () {
  35636. scope.manager.itemEnd( url );
  35637. }, undefined, function () {
  35638. scope.manager.itemError( url );
  35639. scope.manager.itemEnd( url );
  35640. } );
  35641. }
  35642. function deserializeImage( image ) {
  35643. if ( typeof image === 'string' ) {
  35644. const url = image;
  35645. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35646. return loadImage( path );
  35647. } else {
  35648. if ( image.data ) {
  35649. return {
  35650. data: getTypedArray( image.type, image.data ),
  35651. width: image.width,
  35652. height: image.height
  35653. };
  35654. } else {
  35655. return null;
  35656. }
  35657. }
  35658. }
  35659. if ( json !== undefined && json.length > 0 ) {
  35660. const manager = new LoadingManager( onLoad );
  35661. loader = new ImageLoader( manager );
  35662. loader.setCrossOrigin( this.crossOrigin );
  35663. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35664. const image = json[ i ];
  35665. const url = image.url;
  35666. if ( Array.isArray( url ) ) {
  35667. // load array of images e.g CubeTexture
  35668. const imageArray = [];
  35669. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35670. const currentUrl = url[ j ];
  35671. const deserializedImage = deserializeImage( currentUrl );
  35672. if ( deserializedImage !== null ) {
  35673. if ( deserializedImage instanceof HTMLImageElement ) {
  35674. imageArray.push( deserializedImage );
  35675. } else {
  35676. // special case: handle array of data textures for cube textures
  35677. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35678. }
  35679. }
  35680. }
  35681. images[ image.uuid ] = new Source( imageArray );
  35682. } else {
  35683. // load single image
  35684. const deserializedImage = deserializeImage( image.url );
  35685. images[ image.uuid ] = new Source( deserializedImage );
  35686. }
  35687. }
  35688. }
  35689. return images;
  35690. }
  35691. async parseImagesAsync( json ) {
  35692. const scope = this;
  35693. const images = {};
  35694. let loader;
  35695. async function deserializeImage( image ) {
  35696. if ( typeof image === 'string' ) {
  35697. const url = image;
  35698. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35699. return await loader.loadAsync( path );
  35700. } else {
  35701. if ( image.data ) {
  35702. return {
  35703. data: getTypedArray( image.type, image.data ),
  35704. width: image.width,
  35705. height: image.height
  35706. };
  35707. } else {
  35708. return null;
  35709. }
  35710. }
  35711. }
  35712. if ( json !== undefined && json.length > 0 ) {
  35713. loader = new ImageLoader( this.manager );
  35714. loader.setCrossOrigin( this.crossOrigin );
  35715. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35716. const image = json[ i ];
  35717. const url = image.url;
  35718. if ( Array.isArray( url ) ) {
  35719. // load array of images e.g CubeTexture
  35720. const imageArray = [];
  35721. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35722. const currentUrl = url[ j ];
  35723. const deserializedImage = await deserializeImage( currentUrl );
  35724. if ( deserializedImage !== null ) {
  35725. if ( deserializedImage instanceof HTMLImageElement ) {
  35726. imageArray.push( deserializedImage );
  35727. } else {
  35728. // special case: handle array of data textures for cube textures
  35729. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35730. }
  35731. }
  35732. }
  35733. images[ image.uuid ] = new Source( imageArray );
  35734. } else {
  35735. // load single image
  35736. const deserializedImage = await deserializeImage( image.url );
  35737. images[ image.uuid ] = new Source( deserializedImage );
  35738. }
  35739. }
  35740. }
  35741. return images;
  35742. }
  35743. parseTextures( json, images ) {
  35744. function parseConstant( value, type ) {
  35745. if ( typeof value === 'number' ) return value;
  35746. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35747. return type[ value ];
  35748. }
  35749. const textures = {};
  35750. if ( json !== undefined ) {
  35751. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35752. const data = json[ i ];
  35753. if ( data.image === undefined ) {
  35754. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35755. }
  35756. if ( images[ data.image ] === undefined ) {
  35757. warn( 'ObjectLoader: Undefined image', data.image );
  35758. }
  35759. const source = images[ data.image ];
  35760. const image = source.data;
  35761. let texture;
  35762. if ( Array.isArray( image ) ) {
  35763. texture = new CubeTexture();
  35764. if ( image.length === 6 ) texture.needsUpdate = true;
  35765. } else {
  35766. if ( image && image.data ) {
  35767. texture = new DataTexture();
  35768. } else {
  35769. texture = new Texture();
  35770. }
  35771. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35772. }
  35773. texture.source = source;
  35774. texture.uuid = data.uuid;
  35775. if ( data.name !== undefined ) texture.name = data.name;
  35776. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35777. if ( data.channel !== undefined ) texture.channel = data.channel;
  35778. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35779. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35780. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35781. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35782. if ( data.wrap !== undefined ) {
  35783. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35784. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35785. }
  35786. if ( data.format !== undefined ) texture.format = data.format;
  35787. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35788. if ( data.type !== undefined ) texture.type = data.type;
  35789. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35790. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35791. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35792. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35793. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35794. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35795. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35796. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35797. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35798. if ( data.userData !== undefined ) texture.userData = data.userData;
  35799. textures[ data.uuid ] = texture;
  35800. }
  35801. }
  35802. return textures;
  35803. }
  35804. parseObject( data, geometries, materials, textures, animations ) {
  35805. let object;
  35806. function getGeometry( name ) {
  35807. if ( geometries[ name ] === undefined ) {
  35808. warn( 'ObjectLoader: Undefined geometry', name );
  35809. }
  35810. return geometries[ name ];
  35811. }
  35812. function getMaterial( name ) {
  35813. if ( name === undefined ) return undefined;
  35814. if ( Array.isArray( name ) ) {
  35815. const array = [];
  35816. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35817. const uuid = name[ i ];
  35818. if ( materials[ uuid ] === undefined ) {
  35819. warn( 'ObjectLoader: Undefined material', uuid );
  35820. }
  35821. array.push( materials[ uuid ] );
  35822. }
  35823. return array;
  35824. }
  35825. if ( materials[ name ] === undefined ) {
  35826. warn( 'ObjectLoader: Undefined material', name );
  35827. }
  35828. return materials[ name ];
  35829. }
  35830. function getTexture( uuid ) {
  35831. if ( textures[ uuid ] === undefined ) {
  35832. warn( 'ObjectLoader: Undefined texture', uuid );
  35833. }
  35834. return textures[ uuid ];
  35835. }
  35836. let geometry, material;
  35837. switch ( data.type ) {
  35838. case 'Scene':
  35839. object = new Scene();
  35840. if ( data.background !== undefined ) {
  35841. if ( Number.isInteger( data.background ) ) {
  35842. object.background = new Color( data.background );
  35843. } else {
  35844. object.background = getTexture( data.background );
  35845. }
  35846. }
  35847. if ( data.environment !== undefined ) {
  35848. object.environment = getTexture( data.environment );
  35849. }
  35850. if ( data.fog !== undefined ) {
  35851. if ( data.fog.type === 'Fog' ) {
  35852. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35853. } else if ( data.fog.type === 'FogExp2' ) {
  35854. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35855. }
  35856. if ( data.fog.name !== '' ) {
  35857. object.fog.name = data.fog.name;
  35858. }
  35859. }
  35860. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35861. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35862. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35863. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35864. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35865. break;
  35866. case 'PerspectiveCamera':
  35867. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35868. if ( data.focus !== undefined ) object.focus = data.focus;
  35869. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35870. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35871. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35872. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35873. break;
  35874. case 'OrthographicCamera':
  35875. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35876. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35877. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35878. break;
  35879. case 'AmbientLight':
  35880. object = new AmbientLight( data.color, data.intensity );
  35881. break;
  35882. case 'DirectionalLight':
  35883. object = new DirectionalLight( data.color, data.intensity );
  35884. object.target = data.target || '';
  35885. break;
  35886. case 'PointLight':
  35887. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35888. break;
  35889. case 'RectAreaLight':
  35890. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35891. break;
  35892. case 'SpotLight':
  35893. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35894. object.target = data.target || '';
  35895. break;
  35896. case 'HemisphereLight':
  35897. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35898. break;
  35899. case 'LightProbe':
  35900. const sh = new SphericalHarmonics3().fromArray( data.sh );
  35901. object = new LightProbe( sh, data.intensity );
  35902. break;
  35903. case 'SkinnedMesh':
  35904. geometry = getGeometry( data.geometry );
  35905. material = getMaterial( data.material );
  35906. object = new SkinnedMesh( geometry, material );
  35907. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35908. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35909. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35910. break;
  35911. case 'Mesh':
  35912. geometry = getGeometry( data.geometry );
  35913. material = getMaterial( data.material );
  35914. object = new Mesh( geometry, material );
  35915. break;
  35916. case 'InstancedMesh':
  35917. geometry = getGeometry( data.geometry );
  35918. material = getMaterial( data.material );
  35919. const count = data.count;
  35920. const instanceMatrix = data.instanceMatrix;
  35921. const instanceColor = data.instanceColor;
  35922. object = new InstancedMesh( geometry, material, count );
  35923. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35924. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35925. break;
  35926. case 'BatchedMesh':
  35927. geometry = getGeometry( data.geometry );
  35928. material = getMaterial( data.material );
  35929. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35930. object.geometry = geometry;
  35931. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35932. object.sortObjects = data.sortObjects;
  35933. object._drawRanges = data.drawRanges;
  35934. object._reservedRanges = data.reservedRanges;
  35935. object._geometryInfo = data.geometryInfo.map( info => {
  35936. let box = null;
  35937. let sphere = null;
  35938. if ( info.boundingBox !== undefined ) {
  35939. box = new Box3().fromJSON( info.boundingBox );
  35940. }
  35941. if ( info.boundingSphere !== undefined ) {
  35942. sphere = new Sphere().fromJSON( info.boundingSphere );
  35943. }
  35944. return {
  35945. ...info,
  35946. boundingBox: box,
  35947. boundingSphere: sphere
  35948. };
  35949. } );
  35950. object._instanceInfo = data.instanceInfo;
  35951. object._availableInstanceIds = data._availableInstanceIds;
  35952. object._availableGeometryIds = data._availableGeometryIds;
  35953. object._nextIndexStart = data.nextIndexStart;
  35954. object._nextVertexStart = data.nextVertexStart;
  35955. object._geometryCount = data.geometryCount;
  35956. object._maxInstanceCount = data.maxInstanceCount;
  35957. object._maxVertexCount = data.maxVertexCount;
  35958. object._maxIndexCount = data.maxIndexCount;
  35959. object._geometryInitialized = data.geometryInitialized;
  35960. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35961. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35962. if ( data.colorsTexture !== undefined ) {
  35963. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35964. }
  35965. if ( data.boundingSphere !== undefined ) {
  35966. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35967. }
  35968. if ( data.boundingBox !== undefined ) {
  35969. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35970. }
  35971. break;
  35972. case 'LOD':
  35973. object = new LOD();
  35974. break;
  35975. case 'Line':
  35976. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35977. break;
  35978. case 'LineLoop':
  35979. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35980. break;
  35981. case 'LineSegments':
  35982. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35983. break;
  35984. case 'PointCloud':
  35985. case 'Points':
  35986. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35987. break;
  35988. case 'Sprite':
  35989. object = new Sprite( getMaterial( data.material ) );
  35990. break;
  35991. case 'Group':
  35992. object = new Group();
  35993. break;
  35994. case 'Bone':
  35995. object = new Bone();
  35996. break;
  35997. default:
  35998. object = new Object3D();
  35999. }
  36000. object.uuid = data.uuid;
  36001. if ( data.name !== undefined ) object.name = data.name;
  36002. if ( data.matrix !== undefined ) {
  36003. object.matrix.fromArray( data.matrix );
  36004. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  36005. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  36006. } else {
  36007. if ( data.position !== undefined ) object.position.fromArray( data.position );
  36008. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  36009. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  36010. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  36011. }
  36012. if ( data.up !== undefined ) object.up.fromArray( data.up );
  36013. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  36014. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  36015. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  36016. if ( data.shadow ) {
  36017. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  36018. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  36019. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  36020. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  36021. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  36022. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  36023. }
  36024. if ( data.visible !== undefined ) object.visible = data.visible;
  36025. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  36026. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  36027. if ( data.static !== undefined ) object.static = data.static;
  36028. if ( data.userData !== undefined ) object.userData = data.userData;
  36029. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  36030. if ( data.children !== undefined ) {
  36031. const children = data.children;
  36032. for ( let i = 0; i < children.length; i ++ ) {
  36033. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  36034. }
  36035. }
  36036. if ( data.animations !== undefined ) {
  36037. const objectAnimations = data.animations;
  36038. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  36039. const uuid = objectAnimations[ i ];
  36040. object.animations.push( animations[ uuid ] );
  36041. }
  36042. }
  36043. if ( data.type === 'LOD' ) {
  36044. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  36045. const levels = data.levels;
  36046. for ( let l = 0; l < levels.length; l ++ ) {
  36047. const level = levels[ l ];
  36048. const child = object.getObjectByProperty( 'uuid', level.object );
  36049. if ( child !== undefined ) {
  36050. object.addLevel( child, level.distance, level.hysteresis );
  36051. }
  36052. }
  36053. }
  36054. return object;
  36055. }
  36056. bindSkeletons( object, skeletons ) {
  36057. if ( Object.keys( skeletons ).length === 0 ) return;
  36058. object.traverse( function ( child ) {
  36059. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  36060. const skeleton = skeletons[ child.skeleton ];
  36061. if ( skeleton === undefined ) {
  36062. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  36063. } else {
  36064. child.bind( skeleton, child.bindMatrix );
  36065. }
  36066. }
  36067. } );
  36068. }
  36069. bindLightTargets( object ) {
  36070. object.traverse( function ( child ) {
  36071. if ( child.isDirectionalLight || child.isSpotLight ) {
  36072. const uuid = child.target;
  36073. const target = object.getObjectByProperty( 'uuid', uuid );
  36074. if ( target !== undefined ) {
  36075. child.target = target;
  36076. } else {
  36077. child.target = new Object3D();
  36078. }
  36079. }
  36080. } );
  36081. }
  36082. }
  36083. const TEXTURE_MAPPING = {
  36084. UVMapping: UVMapping,
  36085. CubeReflectionMapping: CubeReflectionMapping,
  36086. CubeRefractionMapping: CubeRefractionMapping,
  36087. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  36088. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  36089. CubeUVReflectionMapping: CubeUVReflectionMapping
  36090. };
  36091. const TEXTURE_WRAPPING = {
  36092. RepeatWrapping: RepeatWrapping,
  36093. ClampToEdgeWrapping: ClampToEdgeWrapping,
  36094. MirroredRepeatWrapping: MirroredRepeatWrapping
  36095. };
  36096. const TEXTURE_FILTER = {
  36097. NearestFilter: NearestFilter,
  36098. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  36099. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  36100. LinearFilter: LinearFilter,
  36101. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  36102. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  36103. };
  36104. const _errorMap = new WeakMap();
  36105. /**
  36106. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  36107. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  36108. * textures for rendering.
  36109. *
  36110. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  36111. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  36112. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  36113. *
  36114. * To match the default behaviour of {@link Texture}, the following options are needed:
  36115. *
  36116. * ```js
  36117. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  36118. * ```
  36119. *
  36120. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  36121. *
  36122. * ```js
  36123. * const loader = new THREE.ImageBitmapLoader();
  36124. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  36125. * const imageBitmap = await loader.loadAsync( 'image.png' );
  36126. *
  36127. * const texture = new THREE.Texture( imageBitmap );
  36128. * texture.needsUpdate = true;
  36129. * ```
  36130. *
  36131. * @augments Loader
  36132. */
  36133. class ImageBitmapLoader extends Loader {
  36134. /**
  36135. * Constructs a new image bitmap loader.
  36136. *
  36137. * @param {LoadingManager} [manager] - The loading manager.
  36138. */
  36139. constructor( manager ) {
  36140. super( manager );
  36141. /**
  36142. * This flag can be used for type testing.
  36143. *
  36144. * @type {boolean}
  36145. * @readonly
  36146. * @default true
  36147. */
  36148. this.isImageBitmapLoader = true;
  36149. if ( typeof createImageBitmap === 'undefined' ) {
  36150. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  36151. }
  36152. if ( typeof fetch === 'undefined' ) {
  36153. warn( 'ImageBitmapLoader: fetch() not supported.' );
  36154. }
  36155. /**
  36156. * Represents the loader options.
  36157. *
  36158. * @type {Object}
  36159. * @default {premultiplyAlpha:'none'}
  36160. */
  36161. this.options = { premultiplyAlpha: 'none' };
  36162. /**
  36163. * Used for aborting requests.
  36164. *
  36165. * @private
  36166. * @type {AbortController}
  36167. */
  36168. this._abortController = new AbortController();
  36169. }
  36170. /**
  36171. * Sets the given loader options. The structure of the object must match the `options` parameter of
  36172. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  36173. *
  36174. * @param {Object} options - The loader options to set.
  36175. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  36176. */
  36177. setOptions( options ) {
  36178. this.options = options;
  36179. return this;
  36180. }
  36181. /**
  36182. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  36183. *
  36184. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36185. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  36186. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  36187. * @param {onErrorCallback} onError - Executed when errors occur.
  36188. * @return {ImageBitmap|undefined} The image bitmap.
  36189. */
  36190. load( url, onLoad, onProgress, onError ) {
  36191. if ( url === undefined ) url = '';
  36192. if ( this.path !== undefined ) url = this.path + url;
  36193. url = this.manager.resolveURL( url );
  36194. const scope = this;
  36195. const cached = Cache.get( `image-bitmap:${url}` );
  36196. if ( cached !== undefined ) {
  36197. scope.manager.itemStart( url );
  36198. // If cached is a promise, wait for it to resolve
  36199. if ( cached.then ) {
  36200. cached.then( imageBitmap => {
  36201. // check if there is an error for the cached promise
  36202. if ( _errorMap.has( cached ) === true ) {
  36203. if ( onError ) onError( _errorMap.get( cached ) );
  36204. scope.manager.itemError( url );
  36205. scope.manager.itemEnd( url );
  36206. } else {
  36207. if ( onLoad ) onLoad( imageBitmap );
  36208. scope.manager.itemEnd( url );
  36209. return imageBitmap;
  36210. }
  36211. } );
  36212. return;
  36213. }
  36214. // If cached is not a promise (i.e., it's already an imageBitmap)
  36215. setTimeout( function () {
  36216. if ( onLoad ) onLoad( cached );
  36217. scope.manager.itemEnd( url );
  36218. }, 0 );
  36219. return cached;
  36220. }
  36221. const fetchOptions = {};
  36222. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  36223. fetchOptions.headers = this.requestHeader;
  36224. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  36225. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  36226. return res.blob();
  36227. } ).then( function ( blob ) {
  36228. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  36229. } ).then( function ( imageBitmap ) {
  36230. Cache.add( `image-bitmap:${url}`, imageBitmap );
  36231. if ( onLoad ) onLoad( imageBitmap );
  36232. scope.manager.itemEnd( url );
  36233. return imageBitmap;
  36234. } ).catch( function ( e ) {
  36235. if ( onError ) onError( e );
  36236. _errorMap.set( promise, e );
  36237. Cache.remove( `image-bitmap:${url}` );
  36238. scope.manager.itemError( url );
  36239. scope.manager.itemEnd( url );
  36240. } );
  36241. Cache.add( `image-bitmap:${url}`, promise );
  36242. scope.manager.itemStart( url );
  36243. }
  36244. /**
  36245. * Aborts ongoing fetch requests.
  36246. *
  36247. * @return {ImageBitmapLoader} A reference to this instance.
  36248. */
  36249. abort() {
  36250. this._abortController.abort();
  36251. this._abortController = new AbortController();
  36252. return this;
  36253. }
  36254. }
  36255. let _context;
  36256. /**
  36257. * Manages the global audio context in the engine.
  36258. *
  36259. * @hideconstructor
  36260. */
  36261. class AudioContext {
  36262. /**
  36263. * Returns the global native audio context.
  36264. *
  36265. * @return {AudioContext} The native audio context.
  36266. */
  36267. static getContext() {
  36268. if ( _context === undefined ) {
  36269. _context = new ( window.AudioContext || window.webkitAudioContext )();
  36270. }
  36271. return _context;
  36272. }
  36273. /**
  36274. * Allows to set the global native audio context from outside.
  36275. *
  36276. * @param {AudioContext} value - The native context to set.
  36277. */
  36278. static setContext( value ) {
  36279. _context = value;
  36280. }
  36281. }
  36282. /**
  36283. * Class for loading audio buffers. Audios are internally
  36284. * loaded via {@link FileLoader}.
  36285. *
  36286. * ```js
  36287. * const audioListener = new THREE.AudioListener();
  36288. * const ambientSound = new THREE.Audio( audioListener );
  36289. *
  36290. * const loader = new THREE.AudioLoader();
  36291. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  36292. *
  36293. * ambientSound.setBuffer( audioBuffer );
  36294. * ambientSound.play();
  36295. * ```
  36296. *
  36297. * @augments Loader
  36298. */
  36299. class AudioLoader extends Loader {
  36300. /**
  36301. * Constructs a new audio loader.
  36302. *
  36303. * @param {LoadingManager} [manager] - The loading manager.
  36304. */
  36305. constructor( manager ) {
  36306. super( manager );
  36307. }
  36308. /**
  36309. * Starts loading from the given URL and passes the loaded audio buffer
  36310. * to the `onLoad()` callback.
  36311. *
  36312. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36313. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  36314. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36315. * @param {onErrorCallback} onError - Executed when errors occur.
  36316. */
  36317. load( url, onLoad, onProgress, onError ) {
  36318. const scope = this;
  36319. const loader = new FileLoader( this.manager );
  36320. loader.setResponseType( 'arraybuffer' );
  36321. loader.setPath( this.path );
  36322. loader.setRequestHeader( this.requestHeader );
  36323. loader.setWithCredentials( this.withCredentials );
  36324. loader.load( url, function ( buffer ) {
  36325. try {
  36326. // Create a copy of the buffer. The `decodeAudioData` method
  36327. // detaches the buffer when complete, preventing reuse.
  36328. const bufferCopy = buffer.slice( 0 );
  36329. const context = AudioContext.getContext();
  36330. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  36331. onLoad( audioBuffer );
  36332. } ).catch( handleError );
  36333. } catch ( e ) {
  36334. handleError( e );
  36335. }
  36336. }, onProgress, onError );
  36337. function handleError( e ) {
  36338. if ( onError ) {
  36339. onError( e );
  36340. } else {
  36341. error( e );
  36342. }
  36343. scope.manager.itemError( url );
  36344. }
  36345. }
  36346. }
  36347. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36348. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36349. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36350. /**
  36351. * A special type of camera that uses two perspective cameras with
  36352. * stereoscopic projection. Can be used for rendering stereo effects
  36353. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36354. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36355. */
  36356. class StereoCamera {
  36357. /**
  36358. * Constructs a new stereo camera.
  36359. */
  36360. constructor() {
  36361. /**
  36362. * The type property is used for detecting the object type
  36363. * in context of serialization/deserialization.
  36364. *
  36365. * @type {string}
  36366. * @readonly
  36367. */
  36368. this.type = 'StereoCamera';
  36369. /**
  36370. * The aspect.
  36371. *
  36372. * @type {number}
  36373. * @default 1
  36374. */
  36375. this.aspect = 1;
  36376. /**
  36377. * The eye separation which represents the distance
  36378. * between the left and right camera.
  36379. *
  36380. * @type {number}
  36381. * @default 0.064
  36382. */
  36383. this.eyeSep = 0.064;
  36384. /**
  36385. * The camera representing the left eye. This is added to layer `1` so objects to be
  36386. * rendered by the left camera must also be added to this layer.
  36387. *
  36388. * @type {PerspectiveCamera}
  36389. */
  36390. this.cameraL = new PerspectiveCamera();
  36391. this.cameraL.layers.enable( 1 );
  36392. this.cameraL.matrixAutoUpdate = false;
  36393. /**
  36394. * The camera representing the right eye. This is added to layer `2` so objects to be
  36395. * rendered by the right camera must also be added to this layer.
  36396. *
  36397. * @type {PerspectiveCamera}
  36398. */
  36399. this.cameraR = new PerspectiveCamera();
  36400. this.cameraR.layers.enable( 2 );
  36401. this.cameraR.matrixAutoUpdate = false;
  36402. this._cache = {
  36403. focus: null,
  36404. fov: null,
  36405. aspect: null,
  36406. near: null,
  36407. far: null,
  36408. zoom: null,
  36409. eyeSep: null
  36410. };
  36411. }
  36412. /**
  36413. * Updates the stereo camera based on the given perspective camera.
  36414. *
  36415. * @param {PerspectiveCamera} camera - The perspective camera.
  36416. */
  36417. update( camera ) {
  36418. const cache = this._cache;
  36419. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36420. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36421. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36422. if ( needsUpdate ) {
  36423. cache.focus = camera.focus;
  36424. cache.fov = camera.fov;
  36425. cache.aspect = camera.aspect * this.aspect;
  36426. cache.near = camera.near;
  36427. cache.far = camera.far;
  36428. cache.zoom = camera.zoom;
  36429. cache.eyeSep = this.eyeSep;
  36430. // Off-axis stereoscopic effect based on
  36431. // http://paulbourke.net/stereographics/stereorender/
  36432. _projectionMatrix.copy( camera.projectionMatrix );
  36433. const eyeSepHalf = cache.eyeSep / 2;
  36434. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36435. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36436. let xmin, xmax;
  36437. // translate xOffset
  36438. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36439. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36440. // for left eye
  36441. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36442. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36443. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36444. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36445. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36446. // for right eye
  36447. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36448. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36449. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36450. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36451. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36452. }
  36453. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36454. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36455. }
  36456. }
  36457. /**
  36458. * This type of camera can be used in order to efficiently render a scene with a
  36459. * predefined set of cameras. This is an important performance aspect for
  36460. * rendering VR scenes.
  36461. *
  36462. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36463. * to define for each sub camera the `viewport` property which determines the
  36464. * part of the viewport that is rendered with this camera.
  36465. *
  36466. * @augments PerspectiveCamera
  36467. */
  36468. class ArrayCamera extends PerspectiveCamera {
  36469. /**
  36470. * Constructs a new array camera.
  36471. *
  36472. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36473. */
  36474. constructor( array = [] ) {
  36475. super();
  36476. /**
  36477. * This flag can be used for type testing.
  36478. *
  36479. * @type {boolean}
  36480. * @readonly
  36481. * @default true
  36482. */
  36483. this.isArrayCamera = true;
  36484. /**
  36485. * Whether this camera is used with multiview rendering or not.
  36486. *
  36487. * @type {boolean}
  36488. * @readonly
  36489. * @default false
  36490. */
  36491. this.isMultiViewCamera = false;
  36492. /**
  36493. * An array of perspective sub cameras.
  36494. *
  36495. * @type {Array<PerspectiveCamera>}
  36496. */
  36497. this.cameras = array;
  36498. }
  36499. }
  36500. /**
  36501. * Class for keeping track of time.
  36502. *
  36503. * @deprecated since r183.
  36504. */
  36505. class Clock {
  36506. /**
  36507. * Constructs a new clock.
  36508. *
  36509. * @deprecated since 183.
  36510. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  36511. * `getDelta()` is called for the first time.
  36512. */
  36513. constructor( autoStart = true ) {
  36514. /**
  36515. * If set to `true`, the clock starts automatically when `getDelta()` is called
  36516. * for the first time.
  36517. *
  36518. * @type {boolean}
  36519. * @default true
  36520. */
  36521. this.autoStart = autoStart;
  36522. /**
  36523. * Holds the time at which the clock's `start()` method was last called.
  36524. *
  36525. * @type {number}
  36526. * @default 0
  36527. */
  36528. this.startTime = 0;
  36529. /**
  36530. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  36531. * `getDelta()` methods were last called.
  36532. *
  36533. * @type {number}
  36534. * @default 0
  36535. */
  36536. this.oldTime = 0;
  36537. /**
  36538. * Keeps track of the total time that the clock has been running.
  36539. *
  36540. * @type {number}
  36541. * @default 0
  36542. */
  36543. this.elapsedTime = 0;
  36544. /**
  36545. * Whether the clock is running or not.
  36546. *
  36547. * @type {boolean}
  36548. * @default true
  36549. */
  36550. this.running = false;
  36551. warn( 'THREE.Clock: This module has been deprecated. Please use THREE.Timer instead.' ); // @deprecated, r183
  36552. }
  36553. /**
  36554. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  36555. * called by the class.
  36556. */
  36557. start() {
  36558. this.startTime = performance.now();
  36559. this.oldTime = this.startTime;
  36560. this.elapsedTime = 0;
  36561. this.running = true;
  36562. }
  36563. /**
  36564. * Stops the clock.
  36565. */
  36566. stop() {
  36567. this.getElapsedTime();
  36568. this.running = false;
  36569. this.autoStart = false;
  36570. }
  36571. /**
  36572. * Returns the elapsed time in seconds.
  36573. *
  36574. * @return {number} The elapsed time.
  36575. */
  36576. getElapsedTime() {
  36577. this.getDelta();
  36578. return this.elapsedTime;
  36579. }
  36580. /**
  36581. * Returns the delta time in seconds.
  36582. *
  36583. * @return {number} The delta time.
  36584. */
  36585. getDelta() {
  36586. let diff = 0;
  36587. if ( this.autoStart && ! this.running ) {
  36588. this.start();
  36589. return 0;
  36590. }
  36591. if ( this.running ) {
  36592. const newTime = performance.now();
  36593. diff = ( newTime - this.oldTime ) / 1000;
  36594. this.oldTime = newTime;
  36595. this.elapsedTime += diff;
  36596. }
  36597. return diff;
  36598. }
  36599. }
  36600. const _position$1 = /*@__PURE__*/ new Vector3();
  36601. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36602. const _scale$1 = /*@__PURE__*/ new Vector3();
  36603. const _forward = /*@__PURE__*/ new Vector3();
  36604. const _up = /*@__PURE__*/ new Vector3();
  36605. /**
  36606. * The class represents a virtual listener of the all positional and non-positional audio effects
  36607. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36608. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36609. *
  36610. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36611. * camera represents the 3D transformation of the listener.
  36612. *
  36613. * @augments Object3D
  36614. */
  36615. class AudioListener extends Object3D {
  36616. /**
  36617. * Constructs a new audio listener.
  36618. */
  36619. constructor() {
  36620. super();
  36621. this.type = 'AudioListener';
  36622. /**
  36623. * The native audio context.
  36624. *
  36625. * @type {AudioContext}
  36626. * @readonly
  36627. */
  36628. this.context = AudioContext.getContext();
  36629. /**
  36630. * The gain node used for volume control.
  36631. *
  36632. * @type {GainNode}
  36633. * @readonly
  36634. */
  36635. this.gain = this.context.createGain();
  36636. this.gain.connect( this.context.destination );
  36637. /**
  36638. * An optional filter.
  36639. *
  36640. * Defined via {@link AudioListener#setFilter}.
  36641. *
  36642. * @type {?AudioNode}
  36643. * @default null
  36644. * @readonly
  36645. */
  36646. this.filter = null;
  36647. /**
  36648. * Time delta values required for `linearRampToValueAtTime()` usage.
  36649. *
  36650. * @type {number}
  36651. * @default 0
  36652. * @readonly
  36653. */
  36654. this.timeDelta = 0;
  36655. // private
  36656. this._clock = new Clock();
  36657. }
  36658. /**
  36659. * Returns the listener's input node.
  36660. *
  36661. * This method is used by other audio nodes to connect to this listener.
  36662. *
  36663. * @return {GainNode} The input node.
  36664. */
  36665. getInput() {
  36666. return this.gain;
  36667. }
  36668. /**
  36669. * Removes the current filter from this listener.
  36670. *
  36671. * @return {AudioListener} A reference to this listener.
  36672. */
  36673. removeFilter() {
  36674. if ( this.filter !== null ) {
  36675. this.gain.disconnect( this.filter );
  36676. this.filter.disconnect( this.context.destination );
  36677. this.gain.connect( this.context.destination );
  36678. this.filter = null;
  36679. }
  36680. return this;
  36681. }
  36682. /**
  36683. * Returns the current set filter.
  36684. *
  36685. * @return {?AudioNode} The filter.
  36686. */
  36687. getFilter() {
  36688. return this.filter;
  36689. }
  36690. /**
  36691. * Sets the given filter to this listener.
  36692. *
  36693. * @param {AudioNode} value - The filter to set.
  36694. * @return {AudioListener} A reference to this listener.
  36695. */
  36696. setFilter( value ) {
  36697. if ( this.filter !== null ) {
  36698. this.gain.disconnect( this.filter );
  36699. this.filter.disconnect( this.context.destination );
  36700. } else {
  36701. this.gain.disconnect( this.context.destination );
  36702. }
  36703. this.filter = value;
  36704. this.gain.connect( this.filter );
  36705. this.filter.connect( this.context.destination );
  36706. return this;
  36707. }
  36708. /**
  36709. * Returns the applications master volume.
  36710. *
  36711. * @return {number} The master volume.
  36712. */
  36713. getMasterVolume() {
  36714. return this.gain.gain.value;
  36715. }
  36716. /**
  36717. * Sets the applications master volume. This volume setting affects
  36718. * all audio nodes in the scene.
  36719. *
  36720. * @param {number} value - The master volume to set.
  36721. * @return {AudioListener} A reference to this listener.
  36722. */
  36723. setMasterVolume( value ) {
  36724. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36725. return this;
  36726. }
  36727. updateMatrixWorld( force ) {
  36728. super.updateMatrixWorld( force );
  36729. const listener = this.context.listener;
  36730. this.timeDelta = this._clock.getDelta();
  36731. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36732. // the initial forward and up directions must be orthogonal
  36733. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36734. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36735. if ( listener.positionX ) {
  36736. // code path for Chrome (see #14393)
  36737. const endTime = this.context.currentTime + this.timeDelta;
  36738. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36739. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36740. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36741. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36742. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36743. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36744. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36745. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36746. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36747. } else {
  36748. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36749. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36750. }
  36751. }
  36752. }
  36753. /**
  36754. * Represents a non-positional ( global ) audio object.
  36755. *
  36756. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36757. *
  36758. * ```js
  36759. * // create an AudioListener and add it to the camera
  36760. * const listener = new THREE.AudioListener();
  36761. * camera.add( listener );
  36762. *
  36763. * // create a global audio source
  36764. * const sound = new THREE.Audio( listener );
  36765. *
  36766. * // load a sound and set it as the Audio object's buffer
  36767. * const audioLoader = new THREE.AudioLoader();
  36768. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36769. * sound.setBuffer( buffer );
  36770. * sound.setLoop( true );
  36771. * sound.setVolume( 0.5 );
  36772. * sound.play();
  36773. * });
  36774. * ```
  36775. *
  36776. * @augments Object3D
  36777. */
  36778. class Audio extends Object3D {
  36779. /**
  36780. * Constructs a new audio.
  36781. *
  36782. * @param {AudioListener} listener - The global audio listener.
  36783. */
  36784. constructor( listener ) {
  36785. super();
  36786. this.type = 'Audio';
  36787. /**
  36788. * The global audio listener.
  36789. *
  36790. * @type {AudioListener}
  36791. * @readonly
  36792. */
  36793. this.listener = listener;
  36794. /**
  36795. * The audio context.
  36796. *
  36797. * @type {AudioContext}
  36798. * @readonly
  36799. */
  36800. this.context = listener.context;
  36801. /**
  36802. * The gain node used for volume control.
  36803. *
  36804. * @type {GainNode}
  36805. * @readonly
  36806. */
  36807. this.gain = this.context.createGain();
  36808. this.gain.connect( listener.getInput() );
  36809. /**
  36810. * Whether to start playback automatically or not.
  36811. *
  36812. * @type {boolean}
  36813. * @default false
  36814. */
  36815. this.autoplay = false;
  36816. /**
  36817. * A reference to an audio buffer.
  36818. *
  36819. * Defined via {@link Audio#setBuffer}.
  36820. *
  36821. * @type {?AudioBuffer}
  36822. * @default null
  36823. * @readonly
  36824. */
  36825. this.buffer = null;
  36826. /**
  36827. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36828. * +/- 1200 is an octave.
  36829. *
  36830. * Defined via {@link Audio#setDetune}.
  36831. *
  36832. * @type {number}
  36833. * @default 0
  36834. * @readonly
  36835. */
  36836. this.detune = 0;
  36837. /**
  36838. * Whether the audio should loop or not.
  36839. *
  36840. * Defined via {@link Audio#setLoop}.
  36841. *
  36842. * @type {boolean}
  36843. * @default false
  36844. * @readonly
  36845. */
  36846. this.loop = false;
  36847. /**
  36848. * Defines where in the audio buffer the replay should
  36849. * start, in seconds.
  36850. *
  36851. * @type {number}
  36852. * @default 0
  36853. */
  36854. this.loopStart = 0;
  36855. /**
  36856. * Defines where in the audio buffer the replay should
  36857. * stop, in seconds.
  36858. *
  36859. * @type {number}
  36860. * @default 0
  36861. */
  36862. this.loopEnd = 0;
  36863. /**
  36864. * An offset to the time within the audio buffer the playback
  36865. * should begin, in seconds.
  36866. *
  36867. * @type {number}
  36868. * @default 0
  36869. */
  36870. this.offset = 0;
  36871. /**
  36872. * Overrides the default duration of the audio.
  36873. *
  36874. * @type {undefined|number}
  36875. * @default undefined
  36876. */
  36877. this.duration = undefined;
  36878. /**
  36879. * The playback speed.
  36880. *
  36881. * Defined via {@link Audio#setPlaybackRate}.
  36882. *
  36883. * @type {number}
  36884. * @readonly
  36885. * @default 1
  36886. */
  36887. this.playbackRate = 1;
  36888. /**
  36889. * Indicates whether the audio is playing or not.
  36890. *
  36891. * This flag will be automatically set when using {@link Audio#play},
  36892. * {@link Audio#pause}, {@link Audio#stop}.
  36893. *
  36894. * @type {boolean}
  36895. * @readonly
  36896. * @default false
  36897. */
  36898. this.isPlaying = false;
  36899. /**
  36900. * Indicates whether the audio playback can be controlled
  36901. * with method like {@link Audio#play} or {@link Audio#pause}.
  36902. *
  36903. * This flag will be automatically set when audio sources are
  36904. * defined.
  36905. *
  36906. * @type {boolean}
  36907. * @readonly
  36908. * @default true
  36909. */
  36910. this.hasPlaybackControl = true;
  36911. /**
  36912. * Holds a reference to the current audio source.
  36913. *
  36914. * The property is automatically by one of the `set*()` methods.
  36915. *
  36916. * @type {?AudioNode}
  36917. * @readonly
  36918. * @default null
  36919. */
  36920. this.source = null;
  36921. /**
  36922. * Defines the source type.
  36923. *
  36924. * The property is automatically set by one of the `set*()` methods.
  36925. *
  36926. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36927. * @readonly
  36928. * @default 'empty'
  36929. */
  36930. this.sourceType = 'empty';
  36931. this._startedAt = 0;
  36932. this._progress = 0;
  36933. this._connected = false;
  36934. /**
  36935. * Can be used to apply a variety of low-order filters to create
  36936. * more complex sound effects e.g. via `BiquadFilterNode`.
  36937. *
  36938. * The property is automatically set by {@link Audio#setFilters}.
  36939. *
  36940. * @type {Array<AudioNode>}
  36941. * @readonly
  36942. */
  36943. this.filters = [];
  36944. }
  36945. /**
  36946. * Returns the output audio node.
  36947. *
  36948. * @return {GainNode} The output node.
  36949. */
  36950. getOutput() {
  36951. return this.gain;
  36952. }
  36953. /**
  36954. * Sets the given audio node as the source of this instance.
  36955. *
  36956. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36957. *
  36958. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36959. * @return {Audio} A reference to this instance.
  36960. */
  36961. setNodeSource( audioNode ) {
  36962. this.hasPlaybackControl = false;
  36963. this.sourceType = 'audioNode';
  36964. this.source = audioNode;
  36965. this.connect();
  36966. return this;
  36967. }
  36968. /**
  36969. * Sets the given media element as the source of this instance.
  36970. *
  36971. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36972. *
  36973. * @param {HTMLMediaElement} mediaElement - The media element.
  36974. * @return {Audio} A reference to this instance.
  36975. */
  36976. setMediaElementSource( mediaElement ) {
  36977. this.hasPlaybackControl = false;
  36978. this.sourceType = 'mediaNode';
  36979. this.source = this.context.createMediaElementSource( mediaElement );
  36980. this.connect();
  36981. return this;
  36982. }
  36983. /**
  36984. * Sets the given media stream as the source of this instance.
  36985. *
  36986. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36987. *
  36988. * @param {MediaStream} mediaStream - The media stream.
  36989. * @return {Audio} A reference to this instance.
  36990. */
  36991. setMediaStreamSource( mediaStream ) {
  36992. this.hasPlaybackControl = false;
  36993. this.sourceType = 'mediaStreamNode';
  36994. this.source = this.context.createMediaStreamSource( mediaStream );
  36995. this.connect();
  36996. return this;
  36997. }
  36998. /**
  36999. * Sets the given audio buffer as the source of this instance.
  37000. *
  37001. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  37002. *
  37003. * @param {AudioBuffer} audioBuffer - The audio buffer.
  37004. * @return {Audio} A reference to this instance.
  37005. */
  37006. setBuffer( audioBuffer ) {
  37007. this.buffer = audioBuffer;
  37008. this.sourceType = 'buffer';
  37009. if ( this.autoplay ) this.play();
  37010. return this;
  37011. }
  37012. /**
  37013. * Starts the playback of the audio.
  37014. *
  37015. * Can only be used with compatible audio sources that allow playback control.
  37016. *
  37017. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  37018. * @return {Audio|undefined} A reference to this instance.
  37019. */
  37020. play( delay = 0 ) {
  37021. if ( this.isPlaying === true ) {
  37022. warn( 'Audio: Audio is already playing.' );
  37023. return;
  37024. }
  37025. if ( this.hasPlaybackControl === false ) {
  37026. warn( 'Audio: this Audio has no playback control.' );
  37027. return;
  37028. }
  37029. this._startedAt = this.context.currentTime + delay;
  37030. const source = this.context.createBufferSource();
  37031. source.buffer = this.buffer;
  37032. source.loop = this.loop;
  37033. source.loopStart = this.loopStart;
  37034. source.loopEnd = this.loopEnd;
  37035. source.onended = this.onEnded.bind( this );
  37036. source.start( this._startedAt, this._progress + this.offset, this.duration );
  37037. this.isPlaying = true;
  37038. this.source = source;
  37039. this.setDetune( this.detune );
  37040. this.setPlaybackRate( this.playbackRate );
  37041. return this.connect();
  37042. }
  37043. /**
  37044. * Pauses the playback of the audio.
  37045. *
  37046. * Can only be used with compatible audio sources that allow playback control.
  37047. *
  37048. * @return {Audio|undefined} A reference to this instance.
  37049. */
  37050. pause() {
  37051. if ( this.hasPlaybackControl === false ) {
  37052. warn( 'Audio: this Audio has no playback control.' );
  37053. return;
  37054. }
  37055. if ( this.isPlaying === true ) {
  37056. // update current progress
  37057. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  37058. if ( this.loop === true ) {
  37059. // ensure _progress does not exceed duration with looped audios
  37060. this._progress = this._progress % ( this.duration || this.buffer.duration );
  37061. }
  37062. this.source.stop();
  37063. this.source.onended = null;
  37064. this.isPlaying = false;
  37065. }
  37066. return this;
  37067. }
  37068. /**
  37069. * Stops the playback of the audio.
  37070. *
  37071. * Can only be used with compatible audio sources that allow playback control.
  37072. *
  37073. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  37074. * @return {Audio|undefined} A reference to this instance.
  37075. */
  37076. stop( delay = 0 ) {
  37077. if ( this.hasPlaybackControl === false ) {
  37078. warn( 'Audio: this Audio has no playback control.' );
  37079. return;
  37080. }
  37081. this._progress = 0;
  37082. if ( this.source !== null ) {
  37083. this.source.stop( this.context.currentTime + delay );
  37084. this.source.onended = null;
  37085. }
  37086. this.isPlaying = false;
  37087. return this;
  37088. }
  37089. /**
  37090. * Connects to the audio source. This is used internally on
  37091. * initialisation and when setting / removing filters.
  37092. *
  37093. * @return {Audio} A reference to this instance.
  37094. */
  37095. connect() {
  37096. if ( this.filters.length > 0 ) {
  37097. this.source.connect( this.filters[ 0 ] );
  37098. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37099. this.filters[ i - 1 ].connect( this.filters[ i ] );
  37100. }
  37101. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  37102. } else {
  37103. this.source.connect( this.getOutput() );
  37104. }
  37105. this._connected = true;
  37106. return this;
  37107. }
  37108. /**
  37109. * Disconnects to the audio source. This is used internally on
  37110. * initialisation and when setting / removing filters.
  37111. *
  37112. * @return {Audio|undefined} A reference to this instance.
  37113. */
  37114. disconnect() {
  37115. if ( this._connected === false ) {
  37116. return;
  37117. }
  37118. if ( this.filters.length > 0 ) {
  37119. this.source.disconnect( this.filters[ 0 ] );
  37120. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37121. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  37122. }
  37123. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  37124. } else {
  37125. this.source.disconnect( this.getOutput() );
  37126. }
  37127. this._connected = false;
  37128. return this;
  37129. }
  37130. /**
  37131. * Returns the current set filters.
  37132. *
  37133. * @return {Array<AudioNode>} The list of filters.
  37134. */
  37135. getFilters() {
  37136. return this.filters;
  37137. }
  37138. /**
  37139. * Sets an array of filters and connects them with the audio source.
  37140. *
  37141. * @param {Array<AudioNode>} [value] - A list of filters.
  37142. * @return {Audio} A reference to this instance.
  37143. */
  37144. setFilters( value ) {
  37145. if ( ! value ) value = [];
  37146. if ( this._connected === true ) {
  37147. this.disconnect();
  37148. this.filters = value.slice();
  37149. this.connect();
  37150. } else {
  37151. this.filters = value.slice();
  37152. }
  37153. return this;
  37154. }
  37155. /**
  37156. * Defines the detuning of oscillation in cents.
  37157. *
  37158. * @param {number} value - The detuning of oscillation in cents.
  37159. * @return {Audio} A reference to this instance.
  37160. */
  37161. setDetune( value ) {
  37162. this.detune = value;
  37163. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  37164. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  37165. }
  37166. return this;
  37167. }
  37168. /**
  37169. * Returns the detuning of oscillation in cents.
  37170. *
  37171. * @return {number} The detuning of oscillation in cents.
  37172. */
  37173. getDetune() {
  37174. return this.detune;
  37175. }
  37176. /**
  37177. * Returns the first filter in the list of filters.
  37178. *
  37179. * @return {AudioNode|undefined} The first filter in the list of filters.
  37180. */
  37181. getFilter() {
  37182. return this.getFilters()[ 0 ];
  37183. }
  37184. /**
  37185. * Applies a single filter node to the audio.
  37186. *
  37187. * @param {AudioNode} [filter] - The filter to set.
  37188. * @return {Audio} A reference to this instance.
  37189. */
  37190. setFilter( filter ) {
  37191. return this.setFilters( filter ? [ filter ] : [] );
  37192. }
  37193. /**
  37194. * Sets the playback rate.
  37195. *
  37196. * Can only be used with compatible audio sources that allow playback control.
  37197. *
  37198. * @param {number} [value] - The playback rate to set.
  37199. * @return {Audio|undefined} A reference to this instance.
  37200. */
  37201. setPlaybackRate( value ) {
  37202. if ( this.hasPlaybackControl === false ) {
  37203. warn( 'Audio: this Audio has no playback control.' );
  37204. return;
  37205. }
  37206. this.playbackRate = value;
  37207. if ( this.isPlaying === true ) {
  37208. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  37209. }
  37210. return this;
  37211. }
  37212. /**
  37213. * Returns the current playback rate.
  37214. * @return {number} The playback rate.
  37215. */
  37216. getPlaybackRate() {
  37217. return this.playbackRate;
  37218. }
  37219. /**
  37220. * Automatically called when playback finished.
  37221. */
  37222. onEnded() {
  37223. this.isPlaying = false;
  37224. this._progress = 0;
  37225. }
  37226. /**
  37227. * Returns the loop flag.
  37228. *
  37229. * Can only be used with compatible audio sources that allow playback control.
  37230. *
  37231. * @return {boolean} Whether the audio should loop or not.
  37232. */
  37233. getLoop() {
  37234. if ( this.hasPlaybackControl === false ) {
  37235. warn( 'Audio: this Audio has no playback control.' );
  37236. return false;
  37237. }
  37238. return this.loop;
  37239. }
  37240. /**
  37241. * Sets the loop flag.
  37242. *
  37243. * Can only be used with compatible audio sources that allow playback control.
  37244. *
  37245. * @param {boolean} value - Whether the audio should loop or not.
  37246. * @return {Audio|undefined} A reference to this instance.
  37247. */
  37248. setLoop( value ) {
  37249. if ( this.hasPlaybackControl === false ) {
  37250. warn( 'Audio: this Audio has no playback control.' );
  37251. return;
  37252. }
  37253. this.loop = value;
  37254. if ( this.isPlaying === true ) {
  37255. this.source.loop = this.loop;
  37256. }
  37257. return this;
  37258. }
  37259. /**
  37260. * Sets the loop start value which defines where in the audio buffer the replay should
  37261. * start, in seconds.
  37262. *
  37263. * @param {number} value - The loop start value.
  37264. * @return {Audio} A reference to this instance.
  37265. */
  37266. setLoopStart( value ) {
  37267. this.loopStart = value;
  37268. return this;
  37269. }
  37270. /**
  37271. * Sets the loop end value which defines where in the audio buffer the replay should
  37272. * stop, in seconds.
  37273. *
  37274. * @param {number} value - The loop end value.
  37275. * @return {Audio} A reference to this instance.
  37276. */
  37277. setLoopEnd( value ) {
  37278. this.loopEnd = value;
  37279. return this;
  37280. }
  37281. /**
  37282. * Returns the volume.
  37283. *
  37284. * @return {number} The volume.
  37285. */
  37286. getVolume() {
  37287. return this.gain.gain.value;
  37288. }
  37289. /**
  37290. * Sets the volume.
  37291. *
  37292. * @param {number} value - The volume to set.
  37293. * @return {Audio} A reference to this instance.
  37294. */
  37295. setVolume( value ) {
  37296. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37297. return this;
  37298. }
  37299. copy( source, recursive ) {
  37300. super.copy( source, recursive );
  37301. if ( source.sourceType !== 'buffer' ) {
  37302. warn( 'Audio: Audio source type cannot be copied.' );
  37303. return this;
  37304. }
  37305. this.autoplay = source.autoplay;
  37306. this.buffer = source.buffer;
  37307. this.detune = source.detune;
  37308. this.loop = source.loop;
  37309. this.loopStart = source.loopStart;
  37310. this.loopEnd = source.loopEnd;
  37311. this.offset = source.offset;
  37312. this.duration = source.duration;
  37313. this.playbackRate = source.playbackRate;
  37314. this.hasPlaybackControl = source.hasPlaybackControl;
  37315. this.sourceType = source.sourceType;
  37316. this.filters = source.filters.slice();
  37317. return this;
  37318. }
  37319. clone( recursive ) {
  37320. return new this.constructor( this.listener ).copy( this, recursive );
  37321. }
  37322. }
  37323. const _position = /*@__PURE__*/ new Vector3();
  37324. const _quaternion = /*@__PURE__*/ new Quaternion();
  37325. const _scale = /*@__PURE__*/ new Vector3();
  37326. const _orientation = /*@__PURE__*/ new Vector3();
  37327. /**
  37328. * Represents a positional audio object.
  37329. *
  37330. * ```js
  37331. * // create an AudioListener and add it to the camera
  37332. * const listener = new THREE.AudioListener();
  37333. * camera.add( listener );
  37334. *
  37335. * // create the PositionalAudio object (passing in the listener)
  37336. * const sound = new THREE.PositionalAudio( listener );
  37337. *
  37338. * // load a sound and set it as the PositionalAudio object's buffer
  37339. * const audioLoader = new THREE.AudioLoader();
  37340. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  37341. * sound.setBuffer( buffer );
  37342. * sound.setRefDistance( 20 );
  37343. * sound.play();
  37344. * });
  37345. *
  37346. * // create an object for the sound to play from
  37347. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  37348. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  37349. * const mesh = new THREE.Mesh( sphere, material );
  37350. * scene.add( mesh );
  37351. *
  37352. * // finally add the sound to the mesh
  37353. * mesh.add( sound );
  37354. *
  37355. * @augments Audio
  37356. */
  37357. class PositionalAudio extends Audio {
  37358. /**
  37359. * Constructs a positional audio.
  37360. *
  37361. * @param {AudioListener} listener - The global audio listener.
  37362. */
  37363. constructor( listener ) {
  37364. super( listener );
  37365. /**
  37366. * The panner node represents the location, direction, and behavior of an audio
  37367. * source in 3D space.
  37368. *
  37369. * @type {PannerNode}
  37370. * @readonly
  37371. */
  37372. this.panner = this.context.createPanner();
  37373. this.panner.panningModel = 'HRTF';
  37374. this.panner.connect( this.gain );
  37375. }
  37376. connect() {
  37377. super.connect();
  37378. this.panner.connect( this.gain );
  37379. return this;
  37380. }
  37381. disconnect() {
  37382. super.disconnect();
  37383. this.panner.disconnect( this.gain );
  37384. return this;
  37385. }
  37386. getOutput() {
  37387. return this.panner;
  37388. }
  37389. /**
  37390. * Returns the current reference distance.
  37391. *
  37392. * @return {number} The reference distance.
  37393. */
  37394. getRefDistance() {
  37395. return this.panner.refDistance;
  37396. }
  37397. /**
  37398. * Defines the reference distance for reducing volume as the audio source moves
  37399. * further from the listener – i.e. the distance at which the volume reduction
  37400. * starts taking effect.
  37401. *
  37402. * @param {number} value - The reference distance to set.
  37403. * @return {PositionalAudio} A reference to this instance.
  37404. */
  37405. setRefDistance( value ) {
  37406. this.panner.refDistance = value;
  37407. return this;
  37408. }
  37409. /**
  37410. * Returns the current rolloff factor.
  37411. *
  37412. * @return {number} The rolloff factor.
  37413. */
  37414. getRolloffFactor() {
  37415. return this.panner.rolloffFactor;
  37416. }
  37417. /**
  37418. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37419. *
  37420. * @param {number} value - The rolloff factor.
  37421. * @return {PositionalAudio} A reference to this instance.
  37422. */
  37423. setRolloffFactor( value ) {
  37424. this.panner.rolloffFactor = value;
  37425. return this;
  37426. }
  37427. /**
  37428. * Returns the current distance model.
  37429. *
  37430. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37431. */
  37432. getDistanceModel() {
  37433. return this.panner.distanceModel;
  37434. }
  37435. /**
  37436. * Defines which algorithm to use to reduce the volume of the audio source
  37437. * as it moves away from the listener.
  37438. *
  37439. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37440. * for more details.
  37441. *
  37442. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37443. * @return {PositionalAudio} A reference to this instance.
  37444. */
  37445. setDistanceModel( value ) {
  37446. this.panner.distanceModel = value;
  37447. return this;
  37448. }
  37449. /**
  37450. * Returns the current max distance.
  37451. *
  37452. * @return {number} The max distance.
  37453. */
  37454. getMaxDistance() {
  37455. return this.panner.maxDistance;
  37456. }
  37457. /**
  37458. * Defines the maximum distance between the audio source and the listener,
  37459. * after which the volume is not reduced any further.
  37460. *
  37461. * This value is used only by the `linear` distance model.
  37462. *
  37463. * @param {number} value - The max distance.
  37464. * @return {PositionalAudio} A reference to this instance.
  37465. */
  37466. setMaxDistance( value ) {
  37467. this.panner.maxDistance = value;
  37468. return this;
  37469. }
  37470. /**
  37471. * Sets the directional cone in which the audio can be listened.
  37472. *
  37473. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37474. * @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.
  37475. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37476. * @return {PositionalAudio} A reference to this instance.
  37477. */
  37478. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37479. this.panner.coneInnerAngle = coneInnerAngle;
  37480. this.panner.coneOuterAngle = coneOuterAngle;
  37481. this.panner.coneOuterGain = coneOuterGain;
  37482. return this;
  37483. }
  37484. updateMatrixWorld( force ) {
  37485. super.updateMatrixWorld( force );
  37486. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37487. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37488. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37489. const panner = this.panner;
  37490. if ( panner.positionX ) {
  37491. // code path for Chrome and Firefox (see #14393)
  37492. const endTime = this.context.currentTime + this.listener.timeDelta;
  37493. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37494. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37495. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37496. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37497. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37498. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37499. } else {
  37500. panner.setPosition( _position.x, _position.y, _position.z );
  37501. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37502. }
  37503. }
  37504. }
  37505. /**
  37506. * This class can be used to analyse audio data.
  37507. *
  37508. * ```js
  37509. * // create an AudioListener and add it to the camera
  37510. * const listener = new THREE.AudioListener();
  37511. * camera.add( listener );
  37512. *
  37513. * // create an Audio source
  37514. * const sound = new THREE.Audio( listener );
  37515. *
  37516. * // load a sound and set it as the Audio object's buffer
  37517. * const audioLoader = new THREE.AudioLoader();
  37518. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37519. * sound.setBuffer( buffer );
  37520. * sound.setLoop(true);
  37521. * sound.setVolume(0.5);
  37522. * sound.play();
  37523. * });
  37524. *
  37525. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37526. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37527. *
  37528. * // get the average frequency of the sound
  37529. * const data = analyser.getAverageFrequency();
  37530. * ```
  37531. */
  37532. class AudioAnalyser {
  37533. /**
  37534. * Constructs a new audio analyzer.
  37535. *
  37536. * @param {Audio} audio - The audio to analyze.
  37537. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37538. */
  37539. constructor( audio, fftSize = 2048 ) {
  37540. /**
  37541. * The global audio listener.
  37542. *
  37543. * @type {AnalyserNode}
  37544. */
  37545. this.analyser = audio.context.createAnalyser();
  37546. this.analyser.fftSize = fftSize;
  37547. /**
  37548. * Holds the analyzed data.
  37549. *
  37550. * @type {Uint8Array}
  37551. */
  37552. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37553. audio.getOutput().connect( this.analyser );
  37554. }
  37555. /**
  37556. * Returns an array with frequency data of the audio.
  37557. *
  37558. * Each item in the array represents the decibel value for a specific frequency.
  37559. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37560. * For example, for 48000 sample rate, the last item of the array will represent
  37561. * the decibel value for 24000 Hz.
  37562. *
  37563. * @return {Uint8Array} The frequency data.
  37564. */
  37565. getFrequencyData() {
  37566. this.analyser.getByteFrequencyData( this.data );
  37567. return this.data;
  37568. }
  37569. /**
  37570. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37571. *
  37572. * @return {number} The average frequency.
  37573. */
  37574. getAverageFrequency() {
  37575. let value = 0;
  37576. const data = this.getFrequencyData();
  37577. for ( let i = 0; i < data.length; i ++ ) {
  37578. value += data[ i ];
  37579. }
  37580. return value / data.length;
  37581. }
  37582. }
  37583. /**
  37584. * Buffered scene graph property that allows weighted accumulation; used internally.
  37585. */
  37586. class PropertyMixer {
  37587. /**
  37588. * Constructs a new property mixer.
  37589. *
  37590. * @param {PropertyBinding} binding - The property binding.
  37591. * @param {string} typeName - The keyframe track type name.
  37592. * @param {number} valueSize - The keyframe track value size.
  37593. */
  37594. constructor( binding, typeName, valueSize ) {
  37595. /**
  37596. * The property binding.
  37597. *
  37598. * @type {PropertyBinding}
  37599. */
  37600. this.binding = binding;
  37601. /**
  37602. * The keyframe track value size.
  37603. *
  37604. * @type {number}
  37605. */
  37606. this.valueSize = valueSize;
  37607. let mixFunction,
  37608. mixFunctionAdditive,
  37609. setIdentity;
  37610. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37611. //
  37612. // interpolators can use .buffer as their .result
  37613. // the data then goes to 'incoming'
  37614. //
  37615. // 'accu0' and 'accu1' are used frame-interleaved for
  37616. // the cumulative result and are compared to detect
  37617. // changes
  37618. //
  37619. // 'orig' stores the original state of the property
  37620. //
  37621. // 'add' is used for additive cumulative results
  37622. //
  37623. // 'work' is optional and is only present for quaternion types. It is used
  37624. // to store intermediate quaternion multiplication results
  37625. switch ( typeName ) {
  37626. case 'quaternion':
  37627. mixFunction = this._slerp;
  37628. mixFunctionAdditive = this._slerpAdditive;
  37629. setIdentity = this._setAdditiveIdentityQuaternion;
  37630. this.buffer = new Float64Array( valueSize * 6 );
  37631. this._workIndex = 5;
  37632. break;
  37633. case 'string':
  37634. case 'bool':
  37635. mixFunction = this._select;
  37636. // Use the regular mix function and for additive on these types,
  37637. // additive is not relevant for non-numeric types
  37638. mixFunctionAdditive = this._select;
  37639. setIdentity = this._setAdditiveIdentityOther;
  37640. this.buffer = new Array( valueSize * 5 );
  37641. break;
  37642. default:
  37643. mixFunction = this._lerp;
  37644. mixFunctionAdditive = this._lerpAdditive;
  37645. setIdentity = this._setAdditiveIdentityNumeric;
  37646. this.buffer = new Float64Array( valueSize * 5 );
  37647. }
  37648. this._mixBufferRegion = mixFunction;
  37649. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37650. this._setIdentity = setIdentity;
  37651. this._origIndex = 3;
  37652. this._addIndex = 4;
  37653. /**
  37654. * TODO
  37655. *
  37656. * @type {number}
  37657. * @default 0
  37658. */
  37659. this.cumulativeWeight = 0;
  37660. /**
  37661. * TODO
  37662. *
  37663. * @type {number}
  37664. * @default 0
  37665. */
  37666. this.cumulativeWeightAdditive = 0;
  37667. /**
  37668. * TODO
  37669. *
  37670. * @type {number}
  37671. * @default 0
  37672. */
  37673. this.useCount = 0;
  37674. /**
  37675. * TODO
  37676. *
  37677. * @type {number}
  37678. * @default 0
  37679. */
  37680. this.referenceCount = 0;
  37681. }
  37682. /**
  37683. * Accumulates data in the `incoming` region into `accu<i>`.
  37684. *
  37685. * @param {number} accuIndex - The accumulation index.
  37686. * @param {number} weight - The weight.
  37687. */
  37688. accumulate( accuIndex, weight ) {
  37689. // note: happily accumulating nothing when weight = 0, the caller knows
  37690. // the weight and shouldn't have made the call in the first place
  37691. const buffer = this.buffer,
  37692. stride = this.valueSize,
  37693. offset = accuIndex * stride + stride;
  37694. let currentWeight = this.cumulativeWeight;
  37695. if ( currentWeight === 0 ) {
  37696. // accuN := incoming * weight
  37697. for ( let i = 0; i !== stride; ++ i ) {
  37698. buffer[ offset + i ] = buffer[ i ];
  37699. }
  37700. currentWeight = weight;
  37701. } else {
  37702. // accuN := accuN + incoming * weight
  37703. currentWeight += weight;
  37704. const mix = weight / currentWeight;
  37705. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37706. }
  37707. this.cumulativeWeight = currentWeight;
  37708. }
  37709. /**
  37710. * Accumulates data in the `incoming` region into `add`.
  37711. *
  37712. * @param {number} weight - The weight.
  37713. */
  37714. accumulateAdditive( weight ) {
  37715. const buffer = this.buffer,
  37716. stride = this.valueSize,
  37717. offset = stride * this._addIndex;
  37718. if ( this.cumulativeWeightAdditive === 0 ) {
  37719. // add = identity
  37720. this._setIdentity();
  37721. }
  37722. // add := add + incoming * weight
  37723. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37724. this.cumulativeWeightAdditive += weight;
  37725. }
  37726. /**
  37727. * Applies the state of `accu<i>` to the binding when accus differ.
  37728. *
  37729. * @param {number} accuIndex - The accumulation index.
  37730. */
  37731. apply( accuIndex ) {
  37732. const stride = this.valueSize,
  37733. buffer = this.buffer,
  37734. offset = accuIndex * stride + stride,
  37735. weight = this.cumulativeWeight,
  37736. weightAdditive = this.cumulativeWeightAdditive,
  37737. binding = this.binding;
  37738. this.cumulativeWeight = 0;
  37739. this.cumulativeWeightAdditive = 0;
  37740. if ( weight < 1 ) {
  37741. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37742. const originalValueOffset = stride * this._origIndex;
  37743. this._mixBufferRegion(
  37744. buffer, offset, originalValueOffset, 1 - weight, stride );
  37745. }
  37746. if ( weightAdditive > 0 ) {
  37747. // accuN := accuN + additive accuN
  37748. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37749. }
  37750. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37751. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37752. // value has changed -> update scene graph
  37753. binding.setValue( buffer, offset );
  37754. break;
  37755. }
  37756. }
  37757. }
  37758. /**
  37759. * Remembers the state of the bound property and copy it to both accus.
  37760. */
  37761. saveOriginalState() {
  37762. const binding = this.binding;
  37763. const buffer = this.buffer,
  37764. stride = this.valueSize,
  37765. originalValueOffset = stride * this._origIndex;
  37766. binding.getValue( buffer, originalValueOffset );
  37767. // accu[0..1] := orig -- initially detect changes against the original
  37768. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37769. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37770. }
  37771. // Add to identity for additive
  37772. this._setIdentity();
  37773. this.cumulativeWeight = 0;
  37774. this.cumulativeWeightAdditive = 0;
  37775. }
  37776. /**
  37777. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37778. */
  37779. restoreOriginalState() {
  37780. const originalValueOffset = this.valueSize * 3;
  37781. this.binding.setValue( this.buffer, originalValueOffset );
  37782. }
  37783. // internals
  37784. _setAdditiveIdentityNumeric() {
  37785. const startIndex = this._addIndex * this.valueSize;
  37786. const endIndex = startIndex + this.valueSize;
  37787. for ( let i = startIndex; i < endIndex; i ++ ) {
  37788. this.buffer[ i ] = 0;
  37789. }
  37790. }
  37791. _setAdditiveIdentityQuaternion() {
  37792. this._setAdditiveIdentityNumeric();
  37793. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37794. }
  37795. _setAdditiveIdentityOther() {
  37796. const startIndex = this._origIndex * this.valueSize;
  37797. const targetIndex = this._addIndex * this.valueSize;
  37798. for ( let i = 0; i < this.valueSize; i ++ ) {
  37799. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37800. }
  37801. }
  37802. // mix functions
  37803. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37804. if ( t >= 0.5 ) {
  37805. for ( let i = 0; i !== stride; ++ i ) {
  37806. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37807. }
  37808. }
  37809. }
  37810. _slerp( buffer, dstOffset, srcOffset, t ) {
  37811. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37812. }
  37813. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37814. const workOffset = this._workIndex * stride;
  37815. // Store result in intermediate buffer offset
  37816. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37817. // Slerp to the intermediate result
  37818. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37819. }
  37820. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37821. const s = 1 - t;
  37822. for ( let i = 0; i !== stride; ++ i ) {
  37823. const j = dstOffset + i;
  37824. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37825. }
  37826. }
  37827. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37828. for ( let i = 0; i !== stride; ++ i ) {
  37829. const j = dstOffset + i;
  37830. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37831. }
  37832. }
  37833. }
  37834. // Characters [].:/ are reserved for track binding syntax.
  37835. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37836. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37837. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37838. // only latin characters, and the unicode \p{L} is not yet supported. So
  37839. // instead, we exclude reserved characters and match everything else.
  37840. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37841. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37842. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37843. // be matched to parse the rest of the track name.
  37844. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37845. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37846. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37847. // Object on target node, and accessor. May not contain reserved
  37848. // characters. Accessor may contain any character except closing bracket.
  37849. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37850. // Property and accessor. May not contain reserved characters. Accessor may
  37851. // contain any non-bracket characters.
  37852. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37853. const _trackRe = new RegExp( ''
  37854. + '^'
  37855. + _directoryRe
  37856. + _nodeRe
  37857. + _objectRe
  37858. + _propertyRe
  37859. + '$'
  37860. );
  37861. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37862. class Composite {
  37863. constructor( targetGroup, path, optionalParsedPath ) {
  37864. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37865. this._targetGroup = targetGroup;
  37866. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37867. }
  37868. getValue( array, offset ) {
  37869. this.bind(); // bind all binding
  37870. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37871. binding = this._bindings[ firstValidIndex ];
  37872. // and only call .getValue on the first
  37873. if ( binding !== undefined ) binding.getValue( array, offset );
  37874. }
  37875. setValue( array, offset ) {
  37876. const bindings = this._bindings;
  37877. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37878. bindings[ i ].setValue( array, offset );
  37879. }
  37880. }
  37881. bind() {
  37882. const bindings = this._bindings;
  37883. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37884. bindings[ i ].bind();
  37885. }
  37886. }
  37887. unbind() {
  37888. const bindings = this._bindings;
  37889. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37890. bindings[ i ].unbind();
  37891. }
  37892. }
  37893. }
  37894. // Note: This class uses a State pattern on a per-method basis:
  37895. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37896. // prototype version of these methods with one that represents
  37897. // the bound state. When the property is not found, the methods
  37898. // become no-ops.
  37899. /**
  37900. * This holds a reference to a real property in the scene graph; used internally.
  37901. */
  37902. class PropertyBinding {
  37903. /**
  37904. * Constructs a new property binding.
  37905. *
  37906. * @param {Object} rootNode - The root node.
  37907. * @param {string} path - The path.
  37908. * @param {?Object} [parsedPath] - The parsed path.
  37909. */
  37910. constructor( rootNode, path, parsedPath ) {
  37911. /**
  37912. * The object path to the animated property.
  37913. *
  37914. * @type {string}
  37915. */
  37916. this.path = path;
  37917. /**
  37918. * An object holding information about the path.
  37919. *
  37920. * @type {Object}
  37921. */
  37922. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37923. /**
  37924. * The object owns the animated property.
  37925. *
  37926. * @type {?Object}
  37927. */
  37928. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37929. /**
  37930. * The root node.
  37931. *
  37932. * @type {Object3D|Skeleton}
  37933. */
  37934. this.rootNode = rootNode;
  37935. // initial state of these methods that calls 'bind'
  37936. this.getValue = this._getValue_unbound;
  37937. this.setValue = this._setValue_unbound;
  37938. }
  37939. /**
  37940. * Factory method for creating a property binding from the given parameters.
  37941. *
  37942. * @static
  37943. * @param {Object} root - The root node.
  37944. * @param {string} path - The path.
  37945. * @param {?Object} [parsedPath] - The parsed path.
  37946. * @return {PropertyBinding|Composite} The created property binding or composite.
  37947. */
  37948. static create( root, path, parsedPath ) {
  37949. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37950. return new PropertyBinding( root, path, parsedPath );
  37951. } else {
  37952. return new PropertyBinding.Composite( root, path, parsedPath );
  37953. }
  37954. }
  37955. /**
  37956. * Replaces spaces with underscores and removes unsupported characters from
  37957. * node names, to ensure compatibility with parseTrackName().
  37958. *
  37959. * @param {string} name - Node name to be sanitized.
  37960. * @return {string} The sanitized node name.
  37961. */
  37962. static sanitizeNodeName( name ) {
  37963. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37964. }
  37965. /**
  37966. * Parses the given track name (an object path to an animated property) and
  37967. * returns an object with information about the path. Matches strings in the following forms:
  37968. *
  37969. * - nodeName.property
  37970. * - nodeName.property[accessor]
  37971. * - nodeName.material.property[accessor]
  37972. * - uuid.property[accessor]
  37973. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37974. * - parentName/nodeName.property
  37975. * - parentName/parentName/nodeName.property[index]
  37976. * - .bone[Armature.DEF_cog].position
  37977. * - scene:helium_balloon_model:helium_balloon_model.position
  37978. *
  37979. * @static
  37980. * @param {string} trackName - The track name to parse.
  37981. * @return {Object} The parsed track name as an object.
  37982. */
  37983. static parseTrackName( trackName ) {
  37984. const matches = _trackRe.exec( trackName );
  37985. if ( matches === null ) {
  37986. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37987. }
  37988. const results = {
  37989. // directoryName: matches[ 1 ], // (tschw) currently unused
  37990. nodeName: matches[ 2 ],
  37991. objectName: matches[ 3 ],
  37992. objectIndex: matches[ 4 ],
  37993. propertyName: matches[ 5 ], // required
  37994. propertyIndex: matches[ 6 ]
  37995. };
  37996. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37997. if ( lastDot !== undefined && lastDot !== -1 ) {
  37998. const objectName = results.nodeName.substring( lastDot + 1 );
  37999. // Object names must be checked against an allowlist. Otherwise, there
  38000. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  38001. // 'bar' could be the objectName, or part of a nodeName (which can
  38002. // include '.' characters).
  38003. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  38004. results.nodeName = results.nodeName.substring( 0, lastDot );
  38005. results.objectName = objectName;
  38006. }
  38007. }
  38008. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  38009. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  38010. }
  38011. return results;
  38012. }
  38013. /**
  38014. * Searches for a node in the hierarchy of the given root object by the given
  38015. * node name.
  38016. *
  38017. * @static
  38018. * @param {Object} root - The root object.
  38019. * @param {string|number} nodeName - The name of the node.
  38020. * @return {?Object} The found node. Returns `null` if no object was found.
  38021. */
  38022. static findNode( root, nodeName ) {
  38023. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  38024. return root;
  38025. }
  38026. // search into skeleton bones.
  38027. if ( root.skeleton ) {
  38028. const bone = root.skeleton.getBoneByName( nodeName );
  38029. if ( bone !== undefined ) {
  38030. return bone;
  38031. }
  38032. }
  38033. // search into node subtree.
  38034. if ( root.children ) {
  38035. const searchNodeSubtree = function ( children ) {
  38036. for ( let i = 0; i < children.length; i ++ ) {
  38037. const childNode = children[ i ];
  38038. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  38039. return childNode;
  38040. }
  38041. const result = searchNodeSubtree( childNode.children );
  38042. if ( result ) return result;
  38043. }
  38044. return null;
  38045. };
  38046. const subTreeNode = searchNodeSubtree( root.children );
  38047. if ( subTreeNode ) {
  38048. return subTreeNode;
  38049. }
  38050. }
  38051. return null;
  38052. }
  38053. // these are used to "bind" a nonexistent property
  38054. _getValue_unavailable() {}
  38055. _setValue_unavailable() {}
  38056. // Getters
  38057. _getValue_direct( buffer, offset ) {
  38058. buffer[ offset ] = this.targetObject[ this.propertyName ];
  38059. }
  38060. _getValue_array( buffer, offset ) {
  38061. const source = this.resolvedProperty;
  38062. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  38063. buffer[ offset ++ ] = source[ i ];
  38064. }
  38065. }
  38066. _getValue_arrayElement( buffer, offset ) {
  38067. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  38068. }
  38069. _getValue_toArray( buffer, offset ) {
  38070. this.resolvedProperty.toArray( buffer, offset );
  38071. }
  38072. // Direct
  38073. _setValue_direct( buffer, offset ) {
  38074. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38075. }
  38076. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  38077. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38078. this.targetObject.needsUpdate = true;
  38079. }
  38080. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38081. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38082. this.targetObject.matrixWorldNeedsUpdate = true;
  38083. }
  38084. // EntireArray
  38085. _setValue_array( buffer, offset ) {
  38086. const dest = this.resolvedProperty;
  38087. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38088. dest[ i ] = buffer[ offset ++ ];
  38089. }
  38090. }
  38091. _setValue_array_setNeedsUpdate( buffer, offset ) {
  38092. const dest = this.resolvedProperty;
  38093. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38094. dest[ i ] = buffer[ offset ++ ];
  38095. }
  38096. this.targetObject.needsUpdate = true;
  38097. }
  38098. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38099. const dest = this.resolvedProperty;
  38100. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38101. dest[ i ] = buffer[ offset ++ ];
  38102. }
  38103. this.targetObject.matrixWorldNeedsUpdate = true;
  38104. }
  38105. // ArrayElement
  38106. _setValue_arrayElement( buffer, offset ) {
  38107. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38108. }
  38109. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  38110. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38111. this.targetObject.needsUpdate = true;
  38112. }
  38113. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38114. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38115. this.targetObject.matrixWorldNeedsUpdate = true;
  38116. }
  38117. // HasToFromArray
  38118. _setValue_fromArray( buffer, offset ) {
  38119. this.resolvedProperty.fromArray( buffer, offset );
  38120. }
  38121. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  38122. this.resolvedProperty.fromArray( buffer, offset );
  38123. this.targetObject.needsUpdate = true;
  38124. }
  38125. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38126. this.resolvedProperty.fromArray( buffer, offset );
  38127. this.targetObject.matrixWorldNeedsUpdate = true;
  38128. }
  38129. _getValue_unbound( targetArray, offset ) {
  38130. this.bind();
  38131. this.getValue( targetArray, offset );
  38132. }
  38133. _setValue_unbound( sourceArray, offset ) {
  38134. this.bind();
  38135. this.setValue( sourceArray, offset );
  38136. }
  38137. /**
  38138. * Creates a getter / setter pair for the property tracked by this binding.
  38139. */
  38140. bind() {
  38141. let targetObject = this.node;
  38142. const parsedPath = this.parsedPath;
  38143. const objectName = parsedPath.objectName;
  38144. const propertyName = parsedPath.propertyName;
  38145. let propertyIndex = parsedPath.propertyIndex;
  38146. if ( ! targetObject ) {
  38147. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  38148. this.node = targetObject;
  38149. }
  38150. // set fail state so we can just 'return' on error
  38151. this.getValue = this._getValue_unavailable;
  38152. this.setValue = this._setValue_unavailable;
  38153. // ensure there is a value node
  38154. if ( ! targetObject ) {
  38155. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  38156. return;
  38157. }
  38158. if ( objectName ) {
  38159. let objectIndex = parsedPath.objectIndex;
  38160. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  38161. switch ( objectName ) {
  38162. case 'materials':
  38163. if ( ! targetObject.material ) {
  38164. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38165. return;
  38166. }
  38167. if ( ! targetObject.material.materials ) {
  38168. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  38169. return;
  38170. }
  38171. targetObject = targetObject.material.materials;
  38172. break;
  38173. case 'bones':
  38174. if ( ! targetObject.skeleton ) {
  38175. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  38176. return;
  38177. }
  38178. // potential future optimization: skip this if propertyIndex is already an integer
  38179. // and convert the integer string to a true integer.
  38180. targetObject = targetObject.skeleton.bones;
  38181. // support resolving morphTarget names into indices.
  38182. for ( let i = 0; i < targetObject.length; i ++ ) {
  38183. if ( targetObject[ i ].name === objectIndex ) {
  38184. objectIndex = i;
  38185. break;
  38186. }
  38187. }
  38188. break;
  38189. case 'map':
  38190. if ( 'map' in targetObject ) {
  38191. targetObject = targetObject.map;
  38192. break;
  38193. }
  38194. if ( ! targetObject.material ) {
  38195. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38196. return;
  38197. }
  38198. if ( ! targetObject.material.map ) {
  38199. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  38200. return;
  38201. }
  38202. targetObject = targetObject.material.map;
  38203. break;
  38204. default:
  38205. if ( targetObject[ objectName ] === undefined ) {
  38206. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  38207. return;
  38208. }
  38209. targetObject = targetObject[ objectName ];
  38210. }
  38211. if ( objectIndex !== undefined ) {
  38212. if ( targetObject[ objectIndex ] === undefined ) {
  38213. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  38214. return;
  38215. }
  38216. targetObject = targetObject[ objectIndex ];
  38217. }
  38218. }
  38219. // resolve property
  38220. const nodeProperty = targetObject[ propertyName ];
  38221. if ( nodeProperty === undefined ) {
  38222. const nodeName = parsedPath.nodeName;
  38223. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  38224. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  38225. return;
  38226. }
  38227. // determine versioning scheme
  38228. let versioning = this.Versioning.None;
  38229. this.targetObject = targetObject;
  38230. if ( targetObject.isMaterial === true ) {
  38231. versioning = this.Versioning.NeedsUpdate;
  38232. } else if ( targetObject.isObject3D === true ) {
  38233. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  38234. }
  38235. // determine how the property gets bound
  38236. let bindingType = this.BindingType.Direct;
  38237. if ( propertyIndex !== undefined ) {
  38238. // access a sub element of the property array (only primitives are supported right now)
  38239. if ( propertyName === 'morphTargetInfluences' ) {
  38240. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  38241. // support resolving morphTarget names into indices.
  38242. if ( ! targetObject.geometry ) {
  38243. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  38244. return;
  38245. }
  38246. if ( ! targetObject.geometry.morphAttributes ) {
  38247. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  38248. return;
  38249. }
  38250. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  38251. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  38252. }
  38253. }
  38254. bindingType = this.BindingType.ArrayElement;
  38255. this.resolvedProperty = nodeProperty;
  38256. this.propertyIndex = propertyIndex;
  38257. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  38258. // must use copy for Object3D.Euler/Quaternion
  38259. bindingType = this.BindingType.HasFromToArray;
  38260. this.resolvedProperty = nodeProperty;
  38261. } else if ( Array.isArray( nodeProperty ) ) {
  38262. bindingType = this.BindingType.EntireArray;
  38263. this.resolvedProperty = nodeProperty;
  38264. } else {
  38265. this.propertyName = propertyName;
  38266. }
  38267. // select getter / setter
  38268. this.getValue = this.GetterByBindingType[ bindingType ];
  38269. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  38270. }
  38271. /**
  38272. * Unbinds the property.
  38273. */
  38274. unbind() {
  38275. this.node = null;
  38276. // back to the prototype version of getValue / setValue
  38277. // note: avoiding to mutate the shape of 'this' via 'delete'
  38278. this.getValue = this._getValue_unbound;
  38279. this.setValue = this._setValue_unbound;
  38280. }
  38281. }
  38282. PropertyBinding.Composite = Composite;
  38283. PropertyBinding.prototype.BindingType = {
  38284. Direct: 0,
  38285. EntireArray: 1,
  38286. ArrayElement: 2,
  38287. HasFromToArray: 3
  38288. };
  38289. PropertyBinding.prototype.Versioning = {
  38290. None: 0,
  38291. NeedsUpdate: 1,
  38292. MatrixWorldNeedsUpdate: 2
  38293. };
  38294. PropertyBinding.prototype.GetterByBindingType = [
  38295. PropertyBinding.prototype._getValue_direct,
  38296. PropertyBinding.prototype._getValue_array,
  38297. PropertyBinding.prototype._getValue_arrayElement,
  38298. PropertyBinding.prototype._getValue_toArray,
  38299. ];
  38300. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  38301. [
  38302. // Direct
  38303. PropertyBinding.prototype._setValue_direct,
  38304. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  38305. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  38306. ], [
  38307. // EntireArray
  38308. PropertyBinding.prototype._setValue_array,
  38309. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  38310. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  38311. ], [
  38312. // ArrayElement
  38313. PropertyBinding.prototype._setValue_arrayElement,
  38314. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  38315. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  38316. ], [
  38317. // HasToFromArray
  38318. PropertyBinding.prototype._setValue_fromArray,
  38319. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  38320. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  38321. ]
  38322. ];
  38323. /**
  38324. * A group of objects that receives a shared animation state.
  38325. *
  38326. * Usage:
  38327. *
  38328. * - Add objects you would otherwise pass as 'root' to the
  38329. * constructor or the .clipAction method of AnimationMixer.
  38330. * - Instead pass this object as 'root'.
  38331. * - You can also add and remove objects later when the mixer is running.
  38332. *
  38333. * Note:
  38334. *
  38335. * - Objects of this class appear as one object to the mixer,
  38336. * so cache control of the individual objects must be done on the group.
  38337. *
  38338. * Limitation:
  38339. *
  38340. * - The animated properties must be compatible among the all objects in the group.
  38341. * - A single property can either be controlled through a target group or directly, but not both.
  38342. */
  38343. class AnimationObjectGroup {
  38344. /**
  38345. * Constructs a new animation group.
  38346. *
  38347. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  38348. */
  38349. constructor() {
  38350. /**
  38351. * This flag can be used for type testing.
  38352. *
  38353. * @type {boolean}
  38354. * @readonly
  38355. * @default true
  38356. */
  38357. this.isAnimationObjectGroup = true;
  38358. /**
  38359. * The UUID of the 3D object.
  38360. *
  38361. * @type {string}
  38362. * @readonly
  38363. */
  38364. this.uuid = generateUUID();
  38365. // cached objects followed by the active ones
  38366. this._objects = Array.prototype.slice.call( arguments );
  38367. this.nCachedObjects_ = 0; // threshold
  38368. // note: read by PropertyBinding.Composite
  38369. const indices = {};
  38370. this._indicesByUUID = indices; // for bookkeeping
  38371. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38372. indices[ arguments[ i ].uuid ] = i;
  38373. }
  38374. this._paths = []; // inside: string
  38375. this._parsedPaths = []; // inside: { we don't care, here }
  38376. this._bindings = []; // inside: Array< PropertyBinding >
  38377. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38378. const scope = this;
  38379. this.stats = {
  38380. objects: {
  38381. get total() {
  38382. return scope._objects.length;
  38383. },
  38384. get inUse() {
  38385. return this.total - scope.nCachedObjects_;
  38386. }
  38387. },
  38388. get bindingsPerObject() {
  38389. return scope._bindings.length;
  38390. }
  38391. };
  38392. }
  38393. /**
  38394. * Adds an arbitrary number of objects to this animation group.
  38395. *
  38396. * @param {...Object3D} arguments - The 3D objects to add.
  38397. */
  38398. add() {
  38399. const objects = this._objects,
  38400. indicesByUUID = this._indicesByUUID,
  38401. paths = this._paths,
  38402. parsedPaths = this._parsedPaths,
  38403. bindings = this._bindings,
  38404. nBindings = bindings.length;
  38405. let knownObject = undefined,
  38406. nObjects = objects.length,
  38407. nCachedObjects = this.nCachedObjects_;
  38408. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38409. const object = arguments[ i ],
  38410. uuid = object.uuid;
  38411. let index = indicesByUUID[ uuid ];
  38412. if ( index === undefined ) {
  38413. // unknown object -> add it to the ACTIVE region
  38414. index = nObjects ++;
  38415. indicesByUUID[ uuid ] = index;
  38416. objects.push( object );
  38417. // accounting is done, now do the same for all bindings
  38418. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38419. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38420. }
  38421. } else if ( index < nCachedObjects ) {
  38422. knownObject = objects[ index ];
  38423. // move existing object to the ACTIVE region
  38424. const firstActiveIndex = -- nCachedObjects,
  38425. lastCachedObject = objects[ firstActiveIndex ];
  38426. indicesByUUID[ lastCachedObject.uuid ] = index;
  38427. objects[ index ] = lastCachedObject;
  38428. indicesByUUID[ uuid ] = firstActiveIndex;
  38429. objects[ firstActiveIndex ] = object;
  38430. // accounting is done, now do the same for all bindings
  38431. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38432. const bindingsForPath = bindings[ j ],
  38433. lastCached = bindingsForPath[ firstActiveIndex ];
  38434. let binding = bindingsForPath[ index ];
  38435. bindingsForPath[ index ] = lastCached;
  38436. if ( binding === undefined ) {
  38437. // since we do not bother to create new bindings
  38438. // for objects that are cached, the binding may
  38439. // or may not exist
  38440. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38441. }
  38442. bindingsForPath[ firstActiveIndex ] = binding;
  38443. }
  38444. } else if ( objects[ index ] !== knownObject ) {
  38445. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38446. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38447. } // else the object is already where we want it to be
  38448. } // for arguments
  38449. this.nCachedObjects_ = nCachedObjects;
  38450. }
  38451. /**
  38452. * Removes an arbitrary number of objects to this animation group
  38453. *
  38454. * @param {...Object3D} arguments - The 3D objects to remove.
  38455. */
  38456. remove() {
  38457. const objects = this._objects,
  38458. indicesByUUID = this._indicesByUUID,
  38459. bindings = this._bindings,
  38460. nBindings = bindings.length;
  38461. let nCachedObjects = this.nCachedObjects_;
  38462. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38463. const object = arguments[ i ],
  38464. uuid = object.uuid,
  38465. index = indicesByUUID[ uuid ];
  38466. if ( index !== undefined && index >= nCachedObjects ) {
  38467. // move existing object into the CACHED region
  38468. const lastCachedIndex = nCachedObjects ++,
  38469. firstActiveObject = objects[ lastCachedIndex ];
  38470. indicesByUUID[ firstActiveObject.uuid ] = index;
  38471. objects[ index ] = firstActiveObject;
  38472. indicesByUUID[ uuid ] = lastCachedIndex;
  38473. objects[ lastCachedIndex ] = object;
  38474. // accounting is done, now do the same for all bindings
  38475. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38476. const bindingsForPath = bindings[ j ],
  38477. firstActive = bindingsForPath[ lastCachedIndex ],
  38478. binding = bindingsForPath[ index ];
  38479. bindingsForPath[ index ] = firstActive;
  38480. bindingsForPath[ lastCachedIndex ] = binding;
  38481. }
  38482. }
  38483. } // for arguments
  38484. this.nCachedObjects_ = nCachedObjects;
  38485. }
  38486. /**
  38487. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38488. *
  38489. * @param {...Object3D} arguments - The 3D objects to uncache.
  38490. */
  38491. uncache() {
  38492. const objects = this._objects,
  38493. indicesByUUID = this._indicesByUUID,
  38494. bindings = this._bindings,
  38495. nBindings = bindings.length;
  38496. let nCachedObjects = this.nCachedObjects_,
  38497. nObjects = objects.length;
  38498. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38499. const object = arguments[ i ],
  38500. uuid = object.uuid,
  38501. index = indicesByUUID[ uuid ];
  38502. if ( index !== undefined ) {
  38503. delete indicesByUUID[ uuid ];
  38504. if ( index < nCachedObjects ) {
  38505. // object is cached, shrink the CACHED region
  38506. const firstActiveIndex = -- nCachedObjects,
  38507. lastCachedObject = objects[ firstActiveIndex ],
  38508. lastIndex = -- nObjects,
  38509. lastObject = objects[ lastIndex ];
  38510. // last cached object takes this object's place
  38511. indicesByUUID[ lastCachedObject.uuid ] = index;
  38512. objects[ index ] = lastCachedObject;
  38513. // last object goes to the activated slot and pop
  38514. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38515. objects[ firstActiveIndex ] = lastObject;
  38516. objects.pop();
  38517. // accounting is done, now do the same for all bindings
  38518. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38519. const bindingsForPath = bindings[ j ],
  38520. lastCached = bindingsForPath[ firstActiveIndex ],
  38521. last = bindingsForPath[ lastIndex ];
  38522. bindingsForPath[ index ] = lastCached;
  38523. bindingsForPath[ firstActiveIndex ] = last;
  38524. bindingsForPath.pop();
  38525. }
  38526. } else {
  38527. // object is active, just swap with the last and pop
  38528. const lastIndex = -- nObjects,
  38529. lastObject = objects[ lastIndex ];
  38530. if ( lastIndex > 0 ) {
  38531. indicesByUUID[ lastObject.uuid ] = index;
  38532. }
  38533. objects[ index ] = lastObject;
  38534. objects.pop();
  38535. // accounting is done, now do the same for all bindings
  38536. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38537. const bindingsForPath = bindings[ j ];
  38538. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38539. bindingsForPath.pop();
  38540. }
  38541. } // cached or active
  38542. } // if object is known
  38543. } // for arguments
  38544. this.nCachedObjects_ = nCachedObjects;
  38545. }
  38546. // Internal interface used by befriended PropertyBinding.Composite:
  38547. subscribe_( path, parsedPath ) {
  38548. // returns an array of bindings for the given path that is changed
  38549. // according to the contained objects in the group
  38550. const indicesByPath = this._bindingsIndicesByPath;
  38551. let index = indicesByPath[ path ];
  38552. const bindings = this._bindings;
  38553. if ( index !== undefined ) return bindings[ index ];
  38554. const paths = this._paths,
  38555. parsedPaths = this._parsedPaths,
  38556. objects = this._objects,
  38557. nObjects = objects.length,
  38558. nCachedObjects = this.nCachedObjects_,
  38559. bindingsForPath = new Array( nObjects );
  38560. index = bindings.length;
  38561. indicesByPath[ path ] = index;
  38562. paths.push( path );
  38563. parsedPaths.push( parsedPath );
  38564. bindings.push( bindingsForPath );
  38565. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38566. const object = objects[ i ];
  38567. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38568. }
  38569. return bindingsForPath;
  38570. }
  38571. unsubscribe_( path ) {
  38572. // tells the group to forget about a property path and no longer
  38573. // update the array previously obtained with 'subscribe_'
  38574. const indicesByPath = this._bindingsIndicesByPath,
  38575. index = indicesByPath[ path ];
  38576. if ( index !== undefined ) {
  38577. const paths = this._paths,
  38578. parsedPaths = this._parsedPaths,
  38579. bindings = this._bindings,
  38580. lastBindingsIndex = bindings.length - 1,
  38581. lastBindings = bindings[ lastBindingsIndex ],
  38582. lastBindingsPath = path[ lastBindingsIndex ];
  38583. indicesByPath[ lastBindingsPath ] = index;
  38584. bindings[ index ] = lastBindings;
  38585. bindings.pop();
  38586. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38587. parsedPaths.pop();
  38588. paths[ index ] = paths[ lastBindingsIndex ];
  38589. paths.pop();
  38590. }
  38591. }
  38592. }
  38593. /**
  38594. * An instance of `AnimationAction` schedules the playback of an animation which is
  38595. * stored in {@link AnimationClip}.
  38596. */
  38597. class AnimationAction {
  38598. /**
  38599. * Constructs a new animation action.
  38600. *
  38601. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38602. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38603. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38604. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38605. */
  38606. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38607. this._mixer = mixer;
  38608. this._clip = clip;
  38609. this._localRoot = localRoot;
  38610. /**
  38611. * Defines how the animation is blended/combined when two or more animations
  38612. * are simultaneously played.
  38613. *
  38614. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38615. */
  38616. this.blendMode = blendMode;
  38617. const tracks = clip.tracks,
  38618. nTracks = tracks.length,
  38619. interpolants = new Array( nTracks );
  38620. const interpolantSettings = {
  38621. endingStart: ZeroCurvatureEnding,
  38622. endingEnd: ZeroCurvatureEnding
  38623. };
  38624. for ( let i = 0; i !== nTracks; ++ i ) {
  38625. const interpolant = tracks[ i ].createInterpolant( null );
  38626. interpolants[ i ] = interpolant;
  38627. interpolant.settings = interpolantSettings;
  38628. }
  38629. this._interpolantSettings = interpolantSettings;
  38630. this._interpolants = interpolants; // bound by the mixer
  38631. // inside: PropertyMixer (managed by the mixer)
  38632. this._propertyBindings = new Array( nTracks );
  38633. this._cacheIndex = null; // for the memory manager
  38634. this._byClipCacheIndex = null; // for the memory manager
  38635. this._timeScaleInterpolant = null;
  38636. this._weightInterpolant = null;
  38637. /**
  38638. * The loop mode, set via {@link AnimationAction#setLoop}.
  38639. *
  38640. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38641. * @default LoopRepeat
  38642. */
  38643. this.loop = LoopRepeat;
  38644. this._loopCount = -1;
  38645. // global mixer time when the action is to be started
  38646. // it's set back to 'null' upon start of the action
  38647. this._startTime = null;
  38648. /**
  38649. * The local time of this action (in seconds, starting with `0`).
  38650. *
  38651. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38652. * loop state).
  38653. *
  38654. * @type {number}
  38655. * @default Infinity
  38656. */
  38657. this.time = 0;
  38658. /**
  38659. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38660. * animation to pause. Negative values cause the animation to play backwards.
  38661. *
  38662. * @type {number}
  38663. * @default 1
  38664. */
  38665. this.timeScale = 1;
  38666. this._effectiveTimeScale = 1;
  38667. /**
  38668. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38669. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38670. * several actions.
  38671. *
  38672. * @type {number}
  38673. * @default 1
  38674. */
  38675. this.weight = 1;
  38676. this._effectiveWeight = 1;
  38677. /**
  38678. * The number of repetitions of the performed clip over the course of this action.
  38679. * Can be set via {@link AnimationAction#setLoop}.
  38680. *
  38681. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38682. * `THREE:LoopOnce`.
  38683. *
  38684. * @type {number}
  38685. * @default Infinity
  38686. */
  38687. this.repetitions = Infinity;
  38688. /**
  38689. * If set to `true`, the playback of the action is paused.
  38690. *
  38691. * @type {boolean}
  38692. * @default false
  38693. */
  38694. this.paused = false;
  38695. /**
  38696. * If set to `false`, the action is disabled so it has no impact.
  38697. *
  38698. * When the action is re-enabled, the animation continues from its current
  38699. * time (setting `enabled` to `false` doesn't reset the action).
  38700. *
  38701. * @type {boolean}
  38702. * @default true
  38703. */
  38704. this.enabled = true;
  38705. /**
  38706. * If set to true the animation will automatically be paused on its last frame.
  38707. *
  38708. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38709. * to `false` when the last loop of the action has finished, so that this action has
  38710. * no further impact.
  38711. *
  38712. * Note: This member has no impact if the action is interrupted (it
  38713. * has only an effect if its last loop has really finished).
  38714. *
  38715. * @type {boolean}
  38716. * @default false
  38717. */
  38718. this.clampWhenFinished = false;
  38719. /**
  38720. * Enables smooth interpolation without separate clips for start, loop and end.
  38721. *
  38722. * @type {boolean}
  38723. * @default true
  38724. */
  38725. this.zeroSlopeAtStart = true;
  38726. /**
  38727. * Enables smooth interpolation without separate clips for start, loop and end.
  38728. *
  38729. * @type {boolean}
  38730. * @default true
  38731. */
  38732. this.zeroSlopeAtEnd = true;
  38733. }
  38734. /**
  38735. * Starts the playback of the animation.
  38736. *
  38737. * @return {AnimationAction} A reference to this animation action.
  38738. */
  38739. play() {
  38740. this._mixer._activateAction( this );
  38741. return this;
  38742. }
  38743. /**
  38744. * Stops the playback of the animation.
  38745. *
  38746. * @return {AnimationAction} A reference to this animation action.
  38747. */
  38748. stop() {
  38749. this._mixer._deactivateAction( this );
  38750. return this.reset();
  38751. }
  38752. /**
  38753. * Resets the playback of the animation.
  38754. *
  38755. * @return {AnimationAction} A reference to this animation action.
  38756. */
  38757. reset() {
  38758. this.paused = false;
  38759. this.enabled = true;
  38760. this.time = 0; // restart clip
  38761. this._loopCount = -1;// forget previous loops
  38762. this._startTime = null;// forget scheduling
  38763. return this.stopFading().stopWarping();
  38764. }
  38765. /**
  38766. * Returns `true` if the animation is running.
  38767. *
  38768. * @return {boolean} Whether the animation is running or not.
  38769. */
  38770. isRunning() {
  38771. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38772. this._startTime === null && this._mixer._isActiveAction( this );
  38773. }
  38774. /**
  38775. * Returns `true` when {@link AnimationAction#play} has been called.
  38776. *
  38777. * @return {boolean} Whether the animation is scheduled or not.
  38778. */
  38779. isScheduled() {
  38780. return this._mixer._isActiveAction( this );
  38781. }
  38782. /**
  38783. * Defines the time when the animation should start.
  38784. *
  38785. * @param {number} time - The start time in seconds.
  38786. * @return {AnimationAction} A reference to this animation action.
  38787. */
  38788. startAt( time ) {
  38789. this._startTime = time;
  38790. return this;
  38791. }
  38792. /**
  38793. * Configures the loop settings for this action.
  38794. *
  38795. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38796. * @param {number} repetitions - The number of repetitions.
  38797. * @return {AnimationAction} A reference to this animation action.
  38798. */
  38799. setLoop( mode, repetitions ) {
  38800. this.loop = mode;
  38801. this.repetitions = repetitions;
  38802. return this;
  38803. }
  38804. /**
  38805. * Sets the effective weight of this action.
  38806. *
  38807. * An action has no effect and thus an effective weight of zero when the
  38808. * action is disabled.
  38809. *
  38810. * @param {number} weight - The weight to set.
  38811. * @return {AnimationAction} A reference to this animation action.
  38812. */
  38813. setEffectiveWeight( weight ) {
  38814. this.weight = weight;
  38815. // note: same logic as when updated at runtime
  38816. this._effectiveWeight = this.enabled ? weight : 0;
  38817. return this.stopFading();
  38818. }
  38819. /**
  38820. * Returns the effective weight of this action.
  38821. *
  38822. * @return {number} The effective weight.
  38823. */
  38824. getEffectiveWeight() {
  38825. return this._effectiveWeight;
  38826. }
  38827. /**
  38828. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38829. * within the passed time interval.
  38830. *
  38831. * @param {number} duration - The duration of the fade.
  38832. * @return {AnimationAction} A reference to this animation action.
  38833. */
  38834. fadeIn( duration ) {
  38835. return this._scheduleFading( duration, 0, 1 );
  38836. }
  38837. /**
  38838. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38839. * within the passed time interval.
  38840. *
  38841. * @param {number} duration - The duration of the fade.
  38842. * @return {AnimationAction} A reference to this animation action.
  38843. */
  38844. fadeOut( duration ) {
  38845. return this._scheduleFading( duration, 1, 0 );
  38846. }
  38847. /**
  38848. * Causes this action to fade in and the given action to fade out,
  38849. * within the passed time interval.
  38850. *
  38851. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38852. * @param {number} duration - The duration of the fade.
  38853. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38854. * @return {AnimationAction} A reference to this animation action.
  38855. */
  38856. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38857. fadeOutAction.fadeOut( duration );
  38858. this.fadeIn( duration );
  38859. if ( warp === true ) {
  38860. const fadeInDuration = this._clip.duration,
  38861. fadeOutDuration = fadeOutAction._clip.duration,
  38862. startEndRatio = fadeOutDuration / fadeInDuration,
  38863. endStartRatio = fadeInDuration / fadeOutDuration;
  38864. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38865. this.warp( endStartRatio, 1.0, duration );
  38866. }
  38867. return this;
  38868. }
  38869. /**
  38870. * Causes this action to fade out and the given action to fade in,
  38871. * within the passed time interval.
  38872. *
  38873. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38874. * @param {number} duration - The duration of the fade.
  38875. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38876. * @return {AnimationAction} A reference to this animation action.
  38877. */
  38878. crossFadeTo( fadeInAction, duration, warp = false ) {
  38879. return fadeInAction.crossFadeFrom( this, duration, warp );
  38880. }
  38881. /**
  38882. * Stops any fading which is applied to this action.
  38883. *
  38884. * @return {AnimationAction} A reference to this animation action.
  38885. */
  38886. stopFading() {
  38887. const weightInterpolant = this._weightInterpolant;
  38888. if ( weightInterpolant !== null ) {
  38889. this._weightInterpolant = null;
  38890. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38891. }
  38892. return this;
  38893. }
  38894. /**
  38895. * Sets the effective time scale of this action.
  38896. *
  38897. * An action has no effect and thus an effective time scale of zero when the
  38898. * action is paused.
  38899. *
  38900. * @param {number} timeScale - The time scale to set.
  38901. * @return {AnimationAction} A reference to this animation action.
  38902. */
  38903. setEffectiveTimeScale( timeScale ) {
  38904. this.timeScale = timeScale;
  38905. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38906. return this.stopWarping();
  38907. }
  38908. /**
  38909. * Returns the effective time scale of this action.
  38910. *
  38911. * @return {number} The effective time scale.
  38912. */
  38913. getEffectiveTimeScale() {
  38914. return this._effectiveTimeScale;
  38915. }
  38916. /**
  38917. * Sets the duration for a single loop of this action.
  38918. *
  38919. * @param {number} duration - The duration to set.
  38920. * @return {AnimationAction} A reference to this animation action.
  38921. */
  38922. setDuration( duration ) {
  38923. this.timeScale = this._clip.duration / duration;
  38924. return this.stopWarping();
  38925. }
  38926. /**
  38927. * Synchronizes this action with the passed other action.
  38928. *
  38929. * @param {AnimationAction} action - The action to sync with.
  38930. * @return {AnimationAction} A reference to this animation action.
  38931. */
  38932. syncWith( action ) {
  38933. this.time = action.time;
  38934. this.timeScale = action.timeScale;
  38935. return this.stopWarping();
  38936. }
  38937. /**
  38938. * Decelerates this animation's speed to `0` within the passed time interval.
  38939. *
  38940. * @param {number} duration - The duration.
  38941. * @return {AnimationAction} A reference to this animation action.
  38942. */
  38943. halt( duration ) {
  38944. return this.warp( this._effectiveTimeScale, 0, duration );
  38945. }
  38946. /**
  38947. * Changes the playback speed, within the passed time interval, by modifying
  38948. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38949. * `endTimeScale`.
  38950. *
  38951. * @param {number} startTimeScale - The start time scale.
  38952. * @param {number} endTimeScale - The end time scale.
  38953. * @param {number} duration - The duration.
  38954. * @return {AnimationAction} A reference to this animation action.
  38955. */
  38956. warp( startTimeScale, endTimeScale, duration ) {
  38957. const mixer = this._mixer,
  38958. now = mixer.time,
  38959. timeScale = this.timeScale;
  38960. let interpolant = this._timeScaleInterpolant;
  38961. if ( interpolant === null ) {
  38962. interpolant = mixer._lendControlInterpolant();
  38963. this._timeScaleInterpolant = interpolant;
  38964. }
  38965. const times = interpolant.parameterPositions,
  38966. values = interpolant.sampleValues;
  38967. times[ 0 ] = now;
  38968. times[ 1 ] = now + duration;
  38969. values[ 0 ] = startTimeScale / timeScale;
  38970. values[ 1 ] = endTimeScale / timeScale;
  38971. return this;
  38972. }
  38973. /**
  38974. * Stops any scheduled warping which is applied to this action.
  38975. *
  38976. * @return {AnimationAction} A reference to this animation action.
  38977. */
  38978. stopWarping() {
  38979. const timeScaleInterpolant = this._timeScaleInterpolant;
  38980. if ( timeScaleInterpolant !== null ) {
  38981. this._timeScaleInterpolant = null;
  38982. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38983. }
  38984. return this;
  38985. }
  38986. /**
  38987. * Returns the animation mixer of this animation action.
  38988. *
  38989. * @return {AnimationMixer} The animation mixer.
  38990. */
  38991. getMixer() {
  38992. return this._mixer;
  38993. }
  38994. /**
  38995. * Returns the animation clip of this animation action.
  38996. *
  38997. * @return {AnimationClip} The animation clip.
  38998. */
  38999. getClip() {
  39000. return this._clip;
  39001. }
  39002. /**
  39003. * Returns the root object of this animation action.
  39004. *
  39005. * @return {Object3D} The root object.
  39006. */
  39007. getRoot() {
  39008. return this._localRoot || this._mixer._root;
  39009. }
  39010. // Internal
  39011. _update( time, deltaTime, timeDirection, accuIndex ) {
  39012. // called by the mixer
  39013. if ( ! this.enabled ) {
  39014. // call ._updateWeight() to update ._effectiveWeight
  39015. this._updateWeight( time );
  39016. return;
  39017. }
  39018. const startTime = this._startTime;
  39019. if ( startTime !== null ) {
  39020. // check for scheduled start of action
  39021. const timeRunning = ( time - startTime ) * timeDirection;
  39022. if ( timeRunning < 0 || timeDirection === 0 ) {
  39023. deltaTime = 0;
  39024. } else {
  39025. this._startTime = null; // unschedule
  39026. deltaTime = timeDirection * timeRunning;
  39027. }
  39028. }
  39029. // apply time scale and advance time
  39030. deltaTime *= this._updateTimeScale( time );
  39031. const clipTime = this._updateTime( deltaTime );
  39032. // note: _updateTime may disable the action resulting in
  39033. // an effective weight of 0
  39034. const weight = this._updateWeight( time );
  39035. if ( weight > 0 ) {
  39036. const interpolants = this._interpolants;
  39037. const propertyMixers = this._propertyBindings;
  39038. switch ( this.blendMode ) {
  39039. case AdditiveAnimationBlendMode:
  39040. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39041. interpolants[ j ].evaluate( clipTime );
  39042. propertyMixers[ j ].accumulateAdditive( weight );
  39043. }
  39044. break;
  39045. case NormalAnimationBlendMode:
  39046. default:
  39047. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39048. interpolants[ j ].evaluate( clipTime );
  39049. propertyMixers[ j ].accumulate( accuIndex, weight );
  39050. }
  39051. }
  39052. }
  39053. }
  39054. _updateWeight( time ) {
  39055. let weight = 0;
  39056. if ( this.enabled ) {
  39057. weight = this.weight;
  39058. const interpolant = this._weightInterpolant;
  39059. if ( interpolant !== null ) {
  39060. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39061. weight *= interpolantValue;
  39062. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39063. this.stopFading();
  39064. if ( interpolantValue === 0 ) {
  39065. // faded out, disable
  39066. this.enabled = false;
  39067. }
  39068. }
  39069. }
  39070. }
  39071. this._effectiveWeight = weight;
  39072. return weight;
  39073. }
  39074. _updateTimeScale( time ) {
  39075. let timeScale = 0;
  39076. if ( ! this.paused ) {
  39077. timeScale = this.timeScale;
  39078. const interpolant = this._timeScaleInterpolant;
  39079. if ( interpolant !== null ) {
  39080. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39081. timeScale *= interpolantValue;
  39082. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39083. this.stopWarping();
  39084. if ( timeScale === 0 ) {
  39085. // motion has halted, pause
  39086. this.paused = true;
  39087. } else {
  39088. // warp done - apply final time scale
  39089. this.timeScale = timeScale;
  39090. }
  39091. }
  39092. }
  39093. }
  39094. this._effectiveTimeScale = timeScale;
  39095. return timeScale;
  39096. }
  39097. _updateTime( deltaTime ) {
  39098. const duration = this._clip.duration;
  39099. const loop = this.loop;
  39100. let time = this.time + deltaTime;
  39101. let loopCount = this._loopCount;
  39102. const pingPong = ( loop === LoopPingPong );
  39103. if ( deltaTime === 0 ) {
  39104. if ( loopCount === -1 ) return time;
  39105. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  39106. }
  39107. if ( loop === LoopOnce ) {
  39108. if ( loopCount === -1 ) {
  39109. // just started
  39110. this._loopCount = 0;
  39111. this._setEndings( true, true, false );
  39112. }
  39113. handle_stop: {
  39114. if ( time >= duration ) {
  39115. time = duration;
  39116. } else if ( time < 0 ) {
  39117. time = 0;
  39118. } else {
  39119. this.time = time;
  39120. break handle_stop;
  39121. }
  39122. if ( this.clampWhenFinished ) this.paused = true;
  39123. else this.enabled = false;
  39124. this.time = time;
  39125. this._mixer.dispatchEvent( {
  39126. type: 'finished', action: this,
  39127. direction: deltaTime < 0 ? -1 : 1
  39128. } );
  39129. }
  39130. } else { // repetitive Repeat or PingPong
  39131. if ( loopCount === -1 ) {
  39132. // just started
  39133. if ( deltaTime >= 0 ) {
  39134. loopCount = 0;
  39135. this._setEndings( true, this.repetitions === 0, pingPong );
  39136. } else {
  39137. // when looping in reverse direction, the initial
  39138. // transition through zero counts as a repetition,
  39139. // so leave loopCount at -1
  39140. this._setEndings( this.repetitions === 0, true, pingPong );
  39141. }
  39142. }
  39143. if ( time >= duration || time < 0 ) {
  39144. // wrap around
  39145. const loopDelta = Math.floor( time / duration ); // signed
  39146. time -= duration * loopDelta;
  39147. loopCount += Math.abs( loopDelta );
  39148. const pending = this.repetitions - loopCount;
  39149. if ( pending <= 0 ) {
  39150. // have to stop (switch state, clamp time, fire event)
  39151. if ( this.clampWhenFinished ) this.paused = true;
  39152. else this.enabled = false;
  39153. time = deltaTime > 0 ? duration : 0;
  39154. this.time = time;
  39155. this._mixer.dispatchEvent( {
  39156. type: 'finished', action: this,
  39157. direction: deltaTime > 0 ? 1 : -1
  39158. } );
  39159. } else {
  39160. // keep running
  39161. if ( pending === 1 ) {
  39162. // entering the last round
  39163. const atStart = deltaTime < 0;
  39164. this._setEndings( atStart, ! atStart, pingPong );
  39165. } else {
  39166. this._setEndings( false, false, pingPong );
  39167. }
  39168. this._loopCount = loopCount;
  39169. this.time = time;
  39170. this._mixer.dispatchEvent( {
  39171. type: 'loop', action: this, loopDelta: loopDelta
  39172. } );
  39173. }
  39174. } else {
  39175. this.time = time;
  39176. }
  39177. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  39178. // invert time for the "pong round"
  39179. return duration - time;
  39180. }
  39181. }
  39182. return time;
  39183. }
  39184. _setEndings( atStart, atEnd, pingPong ) {
  39185. const settings = this._interpolantSettings;
  39186. if ( pingPong ) {
  39187. settings.endingStart = ZeroSlopeEnding;
  39188. settings.endingEnd = ZeroSlopeEnding;
  39189. } else {
  39190. // assuming for LoopOnce atStart == atEnd == true
  39191. if ( atStart ) {
  39192. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39193. } else {
  39194. settings.endingStart = WrapAroundEnding;
  39195. }
  39196. if ( atEnd ) {
  39197. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39198. } else {
  39199. settings.endingEnd = WrapAroundEnding;
  39200. }
  39201. }
  39202. }
  39203. _scheduleFading( duration, weightNow, weightThen ) {
  39204. const mixer = this._mixer, now = mixer.time;
  39205. let interpolant = this._weightInterpolant;
  39206. if ( interpolant === null ) {
  39207. interpolant = mixer._lendControlInterpolant();
  39208. this._weightInterpolant = interpolant;
  39209. }
  39210. const times = interpolant.parameterPositions,
  39211. values = interpolant.sampleValues;
  39212. times[ 0 ] = now;
  39213. values[ 0 ] = weightNow;
  39214. times[ 1 ] = now + duration;
  39215. values[ 1 ] = weightThen;
  39216. return this;
  39217. }
  39218. }
  39219. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  39220. /**
  39221. * `AnimationMixer` is a player for animations on a particular object in
  39222. * the scene. When multiple objects in the scene are animated independently,
  39223. * one `AnimationMixer` may be used for each object.
  39224. */
  39225. class AnimationMixer extends EventDispatcher {
  39226. /**
  39227. * Constructs a new animation mixer.
  39228. *
  39229. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  39230. */
  39231. constructor( root ) {
  39232. super();
  39233. this._root = root;
  39234. this._initMemoryManager();
  39235. this._accuIndex = 0;
  39236. /**
  39237. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  39238. *
  39239. * @type {number}
  39240. * @default 0
  39241. */
  39242. this.time = 0;
  39243. /**
  39244. * A scaling factor for the global time.
  39245. *
  39246. * Note: Setting this member to `0` and later back to `1` is a
  39247. * possibility to pause/unpause all actions that are controlled by this
  39248. * mixer.
  39249. *
  39250. * @type {number}
  39251. * @default 1
  39252. */
  39253. this.timeScale = 1.0;
  39254. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  39255. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  39256. }
  39257. }
  39258. _bindAction( action, prototypeAction ) {
  39259. const root = action._localRoot || this._root,
  39260. tracks = action._clip.tracks,
  39261. nTracks = tracks.length,
  39262. bindings = action._propertyBindings,
  39263. interpolants = action._interpolants,
  39264. rootUuid = root.uuid,
  39265. bindingsByRoot = this._bindingsByRootAndName;
  39266. let bindingsByName = bindingsByRoot[ rootUuid ];
  39267. if ( bindingsByName === undefined ) {
  39268. bindingsByName = {};
  39269. bindingsByRoot[ rootUuid ] = bindingsByName;
  39270. }
  39271. for ( let i = 0; i !== nTracks; ++ i ) {
  39272. const track = tracks[ i ],
  39273. trackName = track.name;
  39274. let binding = bindingsByName[ trackName ];
  39275. if ( binding !== undefined ) {
  39276. ++ binding.referenceCount;
  39277. bindings[ i ] = binding;
  39278. } else {
  39279. binding = bindings[ i ];
  39280. if ( binding !== undefined ) {
  39281. // existing binding, make sure the cache knows
  39282. if ( binding._cacheIndex === null ) {
  39283. ++ binding.referenceCount;
  39284. this._addInactiveBinding( binding, rootUuid, trackName );
  39285. }
  39286. continue;
  39287. }
  39288. const path = prototypeAction && prototypeAction.
  39289. _propertyBindings[ i ].binding.parsedPath;
  39290. binding = new PropertyMixer(
  39291. PropertyBinding.create( root, trackName, path ),
  39292. track.ValueTypeName, track.getValueSize() );
  39293. ++ binding.referenceCount;
  39294. this._addInactiveBinding( binding, rootUuid, trackName );
  39295. bindings[ i ] = binding;
  39296. }
  39297. interpolants[ i ].resultBuffer = binding.buffer;
  39298. }
  39299. }
  39300. _activateAction( action ) {
  39301. if ( ! this._isActiveAction( action ) ) {
  39302. if ( action._cacheIndex === null ) {
  39303. // this action has been forgotten by the cache, but the user
  39304. // appears to be still using it -> rebind
  39305. const rootUuid = ( action._localRoot || this._root ).uuid,
  39306. clipUuid = action._clip.uuid,
  39307. actionsForClip = this._actionsByClip[ clipUuid ];
  39308. this._bindAction( action,
  39309. actionsForClip && actionsForClip.knownActions[ 0 ] );
  39310. this._addInactiveAction( action, clipUuid, rootUuid );
  39311. }
  39312. const bindings = action._propertyBindings;
  39313. // increment reference counts / sort out state
  39314. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39315. const binding = bindings[ i ];
  39316. if ( binding.useCount ++ === 0 ) {
  39317. this._lendBinding( binding );
  39318. binding.saveOriginalState();
  39319. }
  39320. }
  39321. this._lendAction( action );
  39322. }
  39323. }
  39324. _deactivateAction( action ) {
  39325. if ( this._isActiveAction( action ) ) {
  39326. const bindings = action._propertyBindings;
  39327. // decrement reference counts / sort out state
  39328. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39329. const binding = bindings[ i ];
  39330. if ( -- binding.useCount === 0 ) {
  39331. binding.restoreOriginalState();
  39332. this._takeBackBinding( binding );
  39333. }
  39334. }
  39335. this._takeBackAction( action );
  39336. }
  39337. }
  39338. // Memory manager
  39339. _initMemoryManager() {
  39340. this._actions = []; // 'nActiveActions' followed by inactive ones
  39341. this._nActiveActions = 0;
  39342. this._actionsByClip = {};
  39343. // inside:
  39344. // {
  39345. // knownActions: Array< AnimationAction > - used as prototypes
  39346. // actionByRoot: AnimationAction - lookup
  39347. // }
  39348. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  39349. this._nActiveBindings = 0;
  39350. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39351. this._controlInterpolants = []; // same game as above
  39352. this._nActiveControlInterpolants = 0;
  39353. const scope = this;
  39354. this.stats = {
  39355. actions: {
  39356. get total() {
  39357. return scope._actions.length;
  39358. },
  39359. get inUse() {
  39360. return scope._nActiveActions;
  39361. }
  39362. },
  39363. bindings: {
  39364. get total() {
  39365. return scope._bindings.length;
  39366. },
  39367. get inUse() {
  39368. return scope._nActiveBindings;
  39369. }
  39370. },
  39371. controlInterpolants: {
  39372. get total() {
  39373. return scope._controlInterpolants.length;
  39374. },
  39375. get inUse() {
  39376. return scope._nActiveControlInterpolants;
  39377. }
  39378. }
  39379. };
  39380. }
  39381. // Memory management for AnimationAction objects
  39382. _isActiveAction( action ) {
  39383. const index = action._cacheIndex;
  39384. return index !== null && index < this._nActiveActions;
  39385. }
  39386. _addInactiveAction( action, clipUuid, rootUuid ) {
  39387. const actions = this._actions,
  39388. actionsByClip = this._actionsByClip;
  39389. let actionsForClip = actionsByClip[ clipUuid ];
  39390. if ( actionsForClip === undefined ) {
  39391. actionsForClip = {
  39392. knownActions: [ action ],
  39393. actionByRoot: {}
  39394. };
  39395. action._byClipCacheIndex = 0;
  39396. actionsByClip[ clipUuid ] = actionsForClip;
  39397. } else {
  39398. const knownActions = actionsForClip.knownActions;
  39399. action._byClipCacheIndex = knownActions.length;
  39400. knownActions.push( action );
  39401. }
  39402. action._cacheIndex = actions.length;
  39403. actions.push( action );
  39404. actionsForClip.actionByRoot[ rootUuid ] = action;
  39405. }
  39406. _removeInactiveAction( action ) {
  39407. const actions = this._actions,
  39408. lastInactiveAction = actions[ actions.length - 1 ],
  39409. cacheIndex = action._cacheIndex;
  39410. lastInactiveAction._cacheIndex = cacheIndex;
  39411. actions[ cacheIndex ] = lastInactiveAction;
  39412. actions.pop();
  39413. action._cacheIndex = null;
  39414. const clipUuid = action._clip.uuid,
  39415. actionsByClip = this._actionsByClip,
  39416. actionsForClip = actionsByClip[ clipUuid ],
  39417. knownActionsForClip = actionsForClip.knownActions,
  39418. lastKnownAction =
  39419. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39420. byClipCacheIndex = action._byClipCacheIndex;
  39421. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39422. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39423. knownActionsForClip.pop();
  39424. action._byClipCacheIndex = null;
  39425. const actionByRoot = actionsForClip.actionByRoot,
  39426. rootUuid = ( action._localRoot || this._root ).uuid;
  39427. delete actionByRoot[ rootUuid ];
  39428. if ( knownActionsForClip.length === 0 ) {
  39429. delete actionsByClip[ clipUuid ];
  39430. }
  39431. this._removeInactiveBindingsForAction( action );
  39432. }
  39433. _removeInactiveBindingsForAction( action ) {
  39434. const bindings = action._propertyBindings;
  39435. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39436. const binding = bindings[ i ];
  39437. if ( -- binding.referenceCount === 0 ) {
  39438. this._removeInactiveBinding( binding );
  39439. }
  39440. }
  39441. }
  39442. _lendAction( action ) {
  39443. // [ active actions | inactive actions ]
  39444. // [ active actions >| inactive actions ]
  39445. // s a
  39446. // <-swap->
  39447. // a s
  39448. const actions = this._actions,
  39449. prevIndex = action._cacheIndex,
  39450. lastActiveIndex = this._nActiveActions ++,
  39451. firstInactiveAction = actions[ lastActiveIndex ];
  39452. action._cacheIndex = lastActiveIndex;
  39453. actions[ lastActiveIndex ] = action;
  39454. firstInactiveAction._cacheIndex = prevIndex;
  39455. actions[ prevIndex ] = firstInactiveAction;
  39456. }
  39457. _takeBackAction( action ) {
  39458. // [ active actions | inactive actions ]
  39459. // [ active actions |< inactive actions ]
  39460. // a s
  39461. // <-swap->
  39462. // s a
  39463. const actions = this._actions,
  39464. prevIndex = action._cacheIndex,
  39465. firstInactiveIndex = -- this._nActiveActions,
  39466. lastActiveAction = actions[ firstInactiveIndex ];
  39467. action._cacheIndex = firstInactiveIndex;
  39468. actions[ firstInactiveIndex ] = action;
  39469. lastActiveAction._cacheIndex = prevIndex;
  39470. actions[ prevIndex ] = lastActiveAction;
  39471. }
  39472. // Memory management for PropertyMixer objects
  39473. _addInactiveBinding( binding, rootUuid, trackName ) {
  39474. const bindingsByRoot = this._bindingsByRootAndName,
  39475. bindings = this._bindings;
  39476. let bindingByName = bindingsByRoot[ rootUuid ];
  39477. if ( bindingByName === undefined ) {
  39478. bindingByName = {};
  39479. bindingsByRoot[ rootUuid ] = bindingByName;
  39480. }
  39481. bindingByName[ trackName ] = binding;
  39482. binding._cacheIndex = bindings.length;
  39483. bindings.push( binding );
  39484. }
  39485. _removeInactiveBinding( binding ) {
  39486. const bindings = this._bindings,
  39487. propBinding = binding.binding,
  39488. rootUuid = propBinding.rootNode.uuid,
  39489. trackName = propBinding.path,
  39490. bindingsByRoot = this._bindingsByRootAndName,
  39491. bindingByName = bindingsByRoot[ rootUuid ],
  39492. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39493. cacheIndex = binding._cacheIndex;
  39494. lastInactiveBinding._cacheIndex = cacheIndex;
  39495. bindings[ cacheIndex ] = lastInactiveBinding;
  39496. bindings.pop();
  39497. delete bindingByName[ trackName ];
  39498. if ( Object.keys( bindingByName ).length === 0 ) {
  39499. delete bindingsByRoot[ rootUuid ];
  39500. }
  39501. }
  39502. _lendBinding( binding ) {
  39503. const bindings = this._bindings,
  39504. prevIndex = binding._cacheIndex,
  39505. lastActiveIndex = this._nActiveBindings ++,
  39506. firstInactiveBinding = bindings[ lastActiveIndex ];
  39507. binding._cacheIndex = lastActiveIndex;
  39508. bindings[ lastActiveIndex ] = binding;
  39509. firstInactiveBinding._cacheIndex = prevIndex;
  39510. bindings[ prevIndex ] = firstInactiveBinding;
  39511. }
  39512. _takeBackBinding( binding ) {
  39513. const bindings = this._bindings,
  39514. prevIndex = binding._cacheIndex,
  39515. firstInactiveIndex = -- this._nActiveBindings,
  39516. lastActiveBinding = bindings[ firstInactiveIndex ];
  39517. binding._cacheIndex = firstInactiveIndex;
  39518. bindings[ firstInactiveIndex ] = binding;
  39519. lastActiveBinding._cacheIndex = prevIndex;
  39520. bindings[ prevIndex ] = lastActiveBinding;
  39521. }
  39522. // Memory management of Interpolants for weight and time scale
  39523. _lendControlInterpolant() {
  39524. const interpolants = this._controlInterpolants,
  39525. lastActiveIndex = this._nActiveControlInterpolants ++;
  39526. let interpolant = interpolants[ lastActiveIndex ];
  39527. if ( interpolant === undefined ) {
  39528. interpolant = new LinearInterpolant(
  39529. new Float32Array( 2 ), new Float32Array( 2 ),
  39530. 1, _controlInterpolantsResultBuffer );
  39531. interpolant.__cacheIndex = lastActiveIndex;
  39532. interpolants[ lastActiveIndex ] = interpolant;
  39533. }
  39534. return interpolant;
  39535. }
  39536. _takeBackControlInterpolant( interpolant ) {
  39537. const interpolants = this._controlInterpolants,
  39538. prevIndex = interpolant.__cacheIndex,
  39539. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39540. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39541. interpolant.__cacheIndex = firstInactiveIndex;
  39542. interpolants[ firstInactiveIndex ] = interpolant;
  39543. lastActiveInterpolant.__cacheIndex = prevIndex;
  39544. interpolants[ prevIndex ] = lastActiveInterpolant;
  39545. }
  39546. /**
  39547. * Returns an instance of {@link AnimationAction} for the passed clip.
  39548. *
  39549. * If an action fitting the clip and root parameters doesn't yet exist, it
  39550. * will be created by this method. Calling this method several times with the
  39551. * same clip and root parameters always returns the same action.
  39552. *
  39553. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39554. * @param {Object3D} [optionalRoot] - An alternative root object.
  39555. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39556. * @return {?AnimationAction} The animation action.
  39557. */
  39558. clipAction( clip, optionalRoot, blendMode ) {
  39559. const root = optionalRoot || this._root,
  39560. rootUuid = root.uuid;
  39561. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39562. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39563. const actionsForClip = this._actionsByClip[ clipUuid ];
  39564. let prototypeAction = null;
  39565. if ( blendMode === undefined ) {
  39566. if ( clipObject !== null ) {
  39567. blendMode = clipObject.blendMode;
  39568. } else {
  39569. blendMode = NormalAnimationBlendMode;
  39570. }
  39571. }
  39572. if ( actionsForClip !== undefined ) {
  39573. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39574. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39575. return existingAction;
  39576. }
  39577. // we know the clip, so we don't have to parse all
  39578. // the bindings again but can just copy
  39579. prototypeAction = actionsForClip.knownActions[ 0 ];
  39580. // also, take the clip from the prototype action
  39581. if ( clipObject === null )
  39582. clipObject = prototypeAction._clip;
  39583. }
  39584. // clip must be known when specified via string
  39585. if ( clipObject === null ) return null;
  39586. // allocate all resources required to run it
  39587. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39588. this._bindAction( newAction, prototypeAction );
  39589. // and make the action known to the memory manager
  39590. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39591. return newAction;
  39592. }
  39593. /**
  39594. * Returns an existing animation action for the passed clip.
  39595. *
  39596. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39597. * @param {Object3D} [optionalRoot] - An alternative root object.
  39598. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39599. */
  39600. existingAction( clip, optionalRoot ) {
  39601. const root = optionalRoot || this._root,
  39602. rootUuid = root.uuid,
  39603. clipObject = typeof clip === 'string' ?
  39604. AnimationClip.findByName( root, clip ) : clip,
  39605. clipUuid = clipObject ? clipObject.uuid : clip,
  39606. actionsForClip = this._actionsByClip[ clipUuid ];
  39607. if ( actionsForClip !== undefined ) {
  39608. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39609. }
  39610. return null;
  39611. }
  39612. /**
  39613. * Deactivates all previously scheduled actions on this mixer.
  39614. *
  39615. * @return {AnimationMixer} A reference to this animation mixer.
  39616. */
  39617. stopAllAction() {
  39618. const actions = this._actions,
  39619. nActions = this._nActiveActions;
  39620. for ( let i = nActions - 1; i >= 0; -- i ) {
  39621. actions[ i ].stop();
  39622. }
  39623. return this;
  39624. }
  39625. /**
  39626. * Advances the global mixer time and updates the animation.
  39627. *
  39628. * This is usually done in the render loop by passing the delta
  39629. * time from {@link Clock} or {@link Timer}.
  39630. *
  39631. * @param {number} deltaTime - The delta time in seconds.
  39632. * @return {AnimationMixer} A reference to this animation mixer.
  39633. */
  39634. update( deltaTime ) {
  39635. deltaTime *= this.timeScale;
  39636. const actions = this._actions,
  39637. nActions = this._nActiveActions,
  39638. time = this.time += deltaTime,
  39639. timeDirection = Math.sign( deltaTime ),
  39640. accuIndex = this._accuIndex ^= 1;
  39641. // run active actions
  39642. for ( let i = 0; i !== nActions; ++ i ) {
  39643. const action = actions[ i ];
  39644. action._update( time, deltaTime, timeDirection, accuIndex );
  39645. }
  39646. // update scene graph
  39647. const bindings = this._bindings,
  39648. nBindings = this._nActiveBindings;
  39649. for ( let i = 0; i !== nBindings; ++ i ) {
  39650. bindings[ i ].apply( accuIndex );
  39651. }
  39652. return this;
  39653. }
  39654. /**
  39655. * Sets the global mixer to a specific time and updates the animation accordingly.
  39656. *
  39657. * This is useful when you need to jump to an exact time in an animation. The
  39658. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39659. *
  39660. * @param {number} time - The time to set in seconds.
  39661. * @return {AnimationMixer} A reference to this animation mixer.
  39662. */
  39663. setTime( time ) {
  39664. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39665. for ( let i = 0; i < this._actions.length; i ++ ) {
  39666. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39667. }
  39668. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39669. }
  39670. /**
  39671. * Returns this mixer's root object.
  39672. *
  39673. * @return {Object3D} The mixer's root object.
  39674. */
  39675. getRoot() {
  39676. return this._root;
  39677. }
  39678. /**
  39679. * Deallocates all memory resources for a clip. Before using this method make
  39680. * sure to call {@link AnimationAction#stop} for all related actions.
  39681. *
  39682. * @param {AnimationClip} clip - The clip to uncache.
  39683. */
  39684. uncacheClip( clip ) {
  39685. const actions = this._actions,
  39686. clipUuid = clip.uuid,
  39687. actionsByClip = this._actionsByClip,
  39688. actionsForClip = actionsByClip[ clipUuid ];
  39689. if ( actionsForClip !== undefined ) {
  39690. // note: just calling _removeInactiveAction would mess up the
  39691. // iteration state and also require updating the state we can
  39692. // just throw away
  39693. const actionsToRemove = actionsForClip.knownActions;
  39694. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39695. const action = actionsToRemove[ i ];
  39696. this._deactivateAction( action );
  39697. const cacheIndex = action._cacheIndex,
  39698. lastInactiveAction = actions[ actions.length - 1 ];
  39699. action._cacheIndex = null;
  39700. action._byClipCacheIndex = null;
  39701. lastInactiveAction._cacheIndex = cacheIndex;
  39702. actions[ cacheIndex ] = lastInactiveAction;
  39703. actions.pop();
  39704. this._removeInactiveBindingsForAction( action );
  39705. }
  39706. delete actionsByClip[ clipUuid ];
  39707. }
  39708. }
  39709. /**
  39710. * Deallocates all memory resources for a root object. Before using this
  39711. * method make sure to call {@link AnimationAction#stop} for all related
  39712. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39713. * mixer operates on a single root.
  39714. *
  39715. * @param {Object3D} root - The root object to uncache.
  39716. */
  39717. uncacheRoot( root ) {
  39718. const rootUuid = root.uuid,
  39719. actionsByClip = this._actionsByClip;
  39720. for ( const clipUuid in actionsByClip ) {
  39721. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39722. action = actionByRoot[ rootUuid ];
  39723. if ( action !== undefined ) {
  39724. this._deactivateAction( action );
  39725. this._removeInactiveAction( action );
  39726. }
  39727. }
  39728. const bindingsByRoot = this._bindingsByRootAndName,
  39729. bindingByName = bindingsByRoot[ rootUuid ];
  39730. if ( bindingByName !== undefined ) {
  39731. for ( const trackName in bindingByName ) {
  39732. const binding = bindingByName[ trackName ];
  39733. binding.restoreOriginalState();
  39734. this._removeInactiveBinding( binding );
  39735. }
  39736. }
  39737. }
  39738. /**
  39739. * Deallocates all memory resources for an action. The action is identified by the
  39740. * given clip and an optional root object. Before using this method make
  39741. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39742. *
  39743. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39744. * @param {Object3D} [optionalRoot] - An alternative root object.
  39745. */
  39746. uncacheAction( clip, optionalRoot ) {
  39747. const action = this.existingAction( clip, optionalRoot );
  39748. if ( action !== null ) {
  39749. this._deactivateAction( action );
  39750. this._removeInactiveAction( action );
  39751. }
  39752. }
  39753. }
  39754. /**
  39755. * Represents a 3D render target.
  39756. *
  39757. * @augments RenderTarget
  39758. */
  39759. class RenderTarget3D extends RenderTarget {
  39760. /**
  39761. * Constructs a new 3D render target.
  39762. *
  39763. * @param {number} [width=1] - The width of the render target.
  39764. * @param {number} [height=1] - The height of the render target.
  39765. * @param {number} [depth=1] - The height of the render target.
  39766. * @param {RenderTarget~Options} [options] - The configuration object.
  39767. */
  39768. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39769. super( width, height, options );
  39770. /**
  39771. * This flag can be used for type testing.
  39772. *
  39773. * @type {boolean}
  39774. * @readonly
  39775. * @default true
  39776. */
  39777. this.isRenderTarget3D = true;
  39778. this.depth = depth;
  39779. /**
  39780. * Overwritten with a different texture type.
  39781. *
  39782. * @type {Data3DTexture}
  39783. */
  39784. this.texture = new Data3DTexture( null, width, height, depth );
  39785. this._setTextureOptions( options );
  39786. this.texture.isRenderTargetTexture = true;
  39787. }
  39788. }
  39789. /**
  39790. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39791. *
  39792. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39793. * ```js
  39794. * uniforms: {
  39795. * time: { value: 1.0 },
  39796. * resolution: new Uniform( new Vector2() )
  39797. * };
  39798. * ```
  39799. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39800. * in {@link WebGLRenderer}.
  39801. */
  39802. class Uniform {
  39803. /**
  39804. * Constructs a new uniform.
  39805. *
  39806. * @param {any} value - The uniform value.
  39807. */
  39808. constructor( value ) {
  39809. /**
  39810. * The uniform value.
  39811. *
  39812. * @type {any}
  39813. */
  39814. this.value = value;
  39815. }
  39816. /**
  39817. * Returns a new uniform with copied values from this instance.
  39818. * If the value has a `clone()` method, the value is cloned as well.
  39819. *
  39820. * @return {Uniform} A clone of this instance.
  39821. */
  39822. clone() {
  39823. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39824. }
  39825. }
  39826. let _id = 0;
  39827. /**
  39828. * A class for managing multiple uniforms in a single group. The renderer will process
  39829. * such a definition as a single UBO.
  39830. *
  39831. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39832. * in {@link WebGLRenderer}.
  39833. *
  39834. * @augments EventDispatcher
  39835. */
  39836. class UniformsGroup extends EventDispatcher {
  39837. /**
  39838. * Constructs a new uniforms group.
  39839. */
  39840. constructor() {
  39841. super();
  39842. /**
  39843. * This flag can be used for type testing.
  39844. *
  39845. * @type {boolean}
  39846. * @readonly
  39847. * @default true
  39848. */
  39849. this.isUniformsGroup = true;
  39850. /**
  39851. * The ID of the 3D object.
  39852. *
  39853. * @name UniformsGroup#id
  39854. * @type {number}
  39855. * @readonly
  39856. */
  39857. Object.defineProperty( this, 'id', { value: _id ++ } );
  39858. /**
  39859. * The name of the uniforms group.
  39860. *
  39861. * @type {string}
  39862. */
  39863. this.name = '';
  39864. /**
  39865. * The buffer usage.
  39866. *
  39867. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39868. * @default StaticDrawUsage
  39869. */
  39870. this.usage = StaticDrawUsage;
  39871. /**
  39872. * An array holding the uniforms.
  39873. *
  39874. * @type {Array<Uniform>}
  39875. */
  39876. this.uniforms = [];
  39877. }
  39878. /**
  39879. * Adds the given uniform to this uniforms group.
  39880. *
  39881. * @param {Uniform} uniform - The uniform to add.
  39882. * @return {UniformsGroup} A reference to this uniforms group.
  39883. */
  39884. add( uniform ) {
  39885. this.uniforms.push( uniform );
  39886. return this;
  39887. }
  39888. /**
  39889. * Removes the given uniform from this uniforms group.
  39890. *
  39891. * @param {Uniform} uniform - The uniform to remove.
  39892. * @return {UniformsGroup} A reference to this uniforms group.
  39893. */
  39894. remove( uniform ) {
  39895. const index = this.uniforms.indexOf( uniform );
  39896. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39897. return this;
  39898. }
  39899. /**
  39900. * Sets the name of this uniforms group.
  39901. *
  39902. * @param {string} name - The name to set.
  39903. * @return {UniformsGroup} A reference to this uniforms group.
  39904. */
  39905. setName( name ) {
  39906. this.name = name;
  39907. return this;
  39908. }
  39909. /**
  39910. * Sets the usage of this uniforms group.
  39911. *
  39912. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39913. * @return {UniformsGroup} A reference to this uniforms group.
  39914. */
  39915. setUsage( value ) {
  39916. this.usage = value;
  39917. return this;
  39918. }
  39919. /**
  39920. * Frees the GPU-related resources allocated by this instance. Call this
  39921. * method whenever this instance is no longer used in your app.
  39922. *
  39923. * @fires Texture#dispose
  39924. */
  39925. dispose() {
  39926. this.dispatchEvent( { type: 'dispose' } );
  39927. }
  39928. /**
  39929. * Copies the values of the given uniforms group to this instance.
  39930. *
  39931. * @param {UniformsGroup} source - The uniforms group to copy.
  39932. * @return {UniformsGroup} A reference to this uniforms group.
  39933. */
  39934. copy( source ) {
  39935. this.name = source.name;
  39936. this.usage = source.usage;
  39937. const uniformsSource = source.uniforms;
  39938. this.uniforms.length = 0;
  39939. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39940. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39941. for ( let j = 0; j < uniforms.length; j ++ ) {
  39942. this.uniforms.push( uniforms[ j ].clone() );
  39943. }
  39944. }
  39945. return this;
  39946. }
  39947. /**
  39948. * Returns a new uniforms group with copied values from this instance.
  39949. *
  39950. * @return {UniformsGroup} A clone of this instance.
  39951. */
  39952. clone() {
  39953. return new this.constructor().copy( this );
  39954. }
  39955. }
  39956. /**
  39957. * An instanced version of an interleaved buffer.
  39958. *
  39959. * @augments InterleavedBuffer
  39960. */
  39961. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39962. /**
  39963. * Constructs a new instanced interleaved buffer.
  39964. *
  39965. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39966. * @param {number} stride - The number of typed-array elements per vertex.
  39967. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39968. */
  39969. constructor( array, stride, meshPerAttribute = 1 ) {
  39970. super( array, stride );
  39971. /**
  39972. * This flag can be used for type testing.
  39973. *
  39974. * @type {boolean}
  39975. * @readonly
  39976. * @default true
  39977. */
  39978. this.isInstancedInterleavedBuffer = true;
  39979. /**
  39980. * Defines how often a value of this buffer attribute should be repeated,
  39981. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39982. *
  39983. * @type {number}
  39984. * @default 1
  39985. */
  39986. this.meshPerAttribute = meshPerAttribute;
  39987. }
  39988. copy( source ) {
  39989. super.copy( source );
  39990. this.meshPerAttribute = source.meshPerAttribute;
  39991. return this;
  39992. }
  39993. clone( data ) {
  39994. const ib = super.clone( data );
  39995. ib.meshPerAttribute = this.meshPerAttribute;
  39996. return ib;
  39997. }
  39998. toJSON( data ) {
  39999. const json = super.toJSON( data );
  40000. json.isInstancedInterleavedBuffer = true;
  40001. json.meshPerAttribute = this.meshPerAttribute;
  40002. return json;
  40003. }
  40004. }
  40005. /**
  40006. * An alternative version of a buffer attribute with more control over the VBO.
  40007. *
  40008. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  40009. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  40010. *
  40011. * The most common use case for this class is when some kind of GPGPU calculation interferes
  40012. * or even produces the VBOs in question.
  40013. *
  40014. * Notice that this class can only be used with {@link WebGLRenderer}.
  40015. */
  40016. class GLBufferAttribute {
  40017. /**
  40018. * Constructs a new GL buffer attribute.
  40019. *
  40020. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  40021. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40022. * @param {number} itemSize - The item size.
  40023. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40024. * @param {number} count - The expected number of vertices in VBO.
  40025. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  40026. */
  40027. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  40028. /**
  40029. * This flag can be used for type testing.
  40030. *
  40031. * @type {boolean}
  40032. * @readonly
  40033. * @default true
  40034. */
  40035. this.isGLBufferAttribute = true;
  40036. /**
  40037. * The name of the buffer attribute.
  40038. *
  40039. * @type {string}
  40040. */
  40041. this.name = '';
  40042. /**
  40043. * The native WebGL buffer.
  40044. *
  40045. * @type {WebGLBuffer}
  40046. */
  40047. this.buffer = buffer;
  40048. /**
  40049. * The native data type.
  40050. *
  40051. * @type {number}
  40052. */
  40053. this.type = type;
  40054. /**
  40055. * The item size, see {@link BufferAttribute#itemSize}.
  40056. *
  40057. * @type {number}
  40058. */
  40059. this.itemSize = itemSize;
  40060. /**
  40061. * The corresponding size (in bytes) for the given `type` parameter.
  40062. *
  40063. * @type {number}
  40064. */
  40065. this.elementSize = elementSize;
  40066. /**
  40067. * The expected number of vertices in VBO.
  40068. *
  40069. * @type {number}
  40070. */
  40071. this.count = count;
  40072. /**
  40073. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  40074. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  40075. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  40076. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  40077. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  40078. *
  40079. * @type {boolean}
  40080. */
  40081. this.normalized = normalized;
  40082. /**
  40083. * A version number, incremented every time the `needsUpdate` is set to `true`.
  40084. *
  40085. * @type {number}
  40086. */
  40087. this.version = 0;
  40088. }
  40089. /**
  40090. * Flag to indicate that this attribute has changed and should be re-sent to
  40091. * the GPU. Set this to `true` when you modify the value of the array.
  40092. *
  40093. * @type {number}
  40094. * @default false
  40095. * @param {boolean} value
  40096. */
  40097. set needsUpdate( value ) {
  40098. if ( value === true ) this.version ++;
  40099. }
  40100. /**
  40101. * Sets the given native WebGL buffer.
  40102. *
  40103. * @param {WebGLBuffer} buffer - The buffer to set.
  40104. * @return {BufferAttribute} A reference to this instance.
  40105. */
  40106. setBuffer( buffer ) {
  40107. this.buffer = buffer;
  40108. return this;
  40109. }
  40110. /**
  40111. * Sets the given native data type and element size.
  40112. *
  40113. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40114. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40115. * @return {BufferAttribute} A reference to this instance.
  40116. */
  40117. setType( type, elementSize ) {
  40118. this.type = type;
  40119. this.elementSize = elementSize;
  40120. return this;
  40121. }
  40122. /**
  40123. * Sets the item size.
  40124. *
  40125. * @param {number} itemSize - The item size.
  40126. * @return {BufferAttribute} A reference to this instance.
  40127. */
  40128. setItemSize( itemSize ) {
  40129. this.itemSize = itemSize;
  40130. return this;
  40131. }
  40132. /**
  40133. * Sets the count (the expected number of vertices in VBO).
  40134. *
  40135. * @param {number} count - The count.
  40136. * @return {BufferAttribute} A reference to this instance.
  40137. */
  40138. setCount( count ) {
  40139. this.count = count;
  40140. return this;
  40141. }
  40142. }
  40143. const _matrix = /*@__PURE__*/ new Matrix4();
  40144. /**
  40145. * This class is designed to assist with raycasting. Raycasting is used for
  40146. * mouse picking (working out what objects in the 3d space the mouse is over)
  40147. * amongst other things.
  40148. */
  40149. class Raycaster {
  40150. /**
  40151. * Constructs a new raycaster.
  40152. *
  40153. * @param {Vector3} origin - The origin vector where the ray casts from.
  40154. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40155. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  40156. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  40157. */
  40158. constructor( origin, direction, near = 0, far = Infinity ) {
  40159. /**
  40160. * The ray used for raycasting.
  40161. *
  40162. * @type {Ray}
  40163. */
  40164. this.ray = new Ray( origin, direction );
  40165. /**
  40166. * All results returned are further away than near. Near can't be negative.
  40167. *
  40168. * @type {number}
  40169. * @default 0
  40170. */
  40171. this.near = near;
  40172. /**
  40173. * All results returned are closer than far. Far can't be lower than near.
  40174. *
  40175. * @type {number}
  40176. * @default Infinity
  40177. */
  40178. this.far = far;
  40179. /**
  40180. * The camera to use when raycasting against view-dependent objects such as
  40181. * billboarded objects like sprites. This field can be set manually or
  40182. * is set when calling `setFromCamera()`.
  40183. *
  40184. * @type {?Camera}
  40185. * @default null
  40186. */
  40187. this.camera = null;
  40188. /**
  40189. * Allows to selectively ignore 3D objects when performing intersection tests.
  40190. * The following code example ensures that only 3D objects on layer `1` will be
  40191. * honored by raycaster.
  40192. * ```js
  40193. * raycaster.layers.set( 1 );
  40194. * object.layers.enable( 1 );
  40195. * ```
  40196. *
  40197. * @type {Layers}
  40198. */
  40199. this.layers = new Layers();
  40200. /**
  40201. * A parameter object that configures the raycasting. It has the structure:
  40202. *
  40203. * ```
  40204. * {
  40205. * Mesh: {},
  40206. * Line: { threshold: 1 },
  40207. * LOD: {},
  40208. * Points: { threshold: 1 },
  40209. * Sprite: {}
  40210. * }
  40211. * ```
  40212. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  40213. *
  40214. * @type {Object}
  40215. */
  40216. this.params = {
  40217. Mesh: {},
  40218. Line: { threshold: 1 },
  40219. LOD: {},
  40220. Points: { threshold: 1 },
  40221. Sprite: {}
  40222. };
  40223. }
  40224. /**
  40225. * Updates the ray with a new origin and direction by copying the values from the arguments.
  40226. *
  40227. * @param {Vector3} origin - The origin vector where the ray casts from.
  40228. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40229. */
  40230. set( origin, direction ) {
  40231. // direction is assumed to be normalized (for accurate distance calculations)
  40232. this.ray.set( origin, direction );
  40233. }
  40234. /**
  40235. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  40236. *
  40237. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  40238. * X and Y components should be between `-1` and `1`.
  40239. * @param {Camera} camera - The camera from which the ray should originate.
  40240. */
  40241. setFromCamera( coords, camera ) {
  40242. if ( camera.isPerspectiveCamera ) {
  40243. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  40244. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  40245. this.camera = camera;
  40246. } else if ( camera.isOrthographicCamera ) {
  40247. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  40248. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  40249. this.camera = camera;
  40250. } else {
  40251. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  40252. }
  40253. }
  40254. /**
  40255. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  40256. *
  40257. * @param {WebXRController} controller - The controller to copy the position and direction from.
  40258. * @return {Raycaster} A reference to this raycaster.
  40259. */
  40260. setFromXRController( controller ) {
  40261. _matrix.identity().extractRotation( controller.matrixWorld );
  40262. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  40263. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  40264. return this;
  40265. }
  40266. /**
  40267. * The intersection point of a raycaster intersection test.
  40268. * @typedef {Object} Raycaster~Intersection
  40269. * @property {number} distance - The distance from the ray's origin to the intersection point.
  40270. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  40271. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  40272. * @property {Vector3} point - The intersection point, in world coordinates.
  40273. * @property {Object} face - The face that has been intersected.
  40274. * @property {number} faceIndex - The face index.
  40275. * @property {Object3D} object - The 3D object that has been intersected.
  40276. * @property {Vector2} uv - U,V coordinates at point of intersection.
  40277. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  40278. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  40279. * @property {number} instanceId - The index number of the instance where the ray
  40280. * intersects the {@link InstancedMesh}.
  40281. */
  40282. /**
  40283. * Checks all intersection between the ray and the object with or without the
  40284. * descendants. Intersections are returned sorted by distance, closest first.
  40285. *
  40286. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  40287. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  40288. * differently to ray casting than lines or points.
  40289. *
  40290. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  40291. * to be detected; intersections of the ray passing through the back of a face will not
  40292. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  40293. * to `THREE.DoubleSide`.
  40294. *
  40295. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  40296. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40297. * Otherwise it only checks intersection with the object.
  40298. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40299. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40300. */
  40301. intersectObject( object, recursive = true, intersects = [] ) {
  40302. intersect( object, this, intersects, recursive );
  40303. intersects.sort( ascSort );
  40304. return intersects;
  40305. }
  40306. /**
  40307. * Checks all intersection between the ray and the objects with or without
  40308. * the descendants. Intersections are returned sorted by distance, closest first.
  40309. *
  40310. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  40311. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40312. * Otherwise it only checks intersection with the object.
  40313. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40314. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40315. */
  40316. intersectObjects( objects, recursive = true, intersects = [] ) {
  40317. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  40318. intersect( objects[ i ], this, intersects, recursive );
  40319. }
  40320. intersects.sort( ascSort );
  40321. return intersects;
  40322. }
  40323. }
  40324. function ascSort( a, b ) {
  40325. return a.distance - b.distance;
  40326. }
  40327. function intersect( object, raycaster, intersects, recursive ) {
  40328. let propagate = true;
  40329. if ( object.layers.test( raycaster.layers ) ) {
  40330. const result = object.raycast( raycaster, intersects );
  40331. if ( result === false ) propagate = false;
  40332. }
  40333. if ( propagate === true && recursive === true ) {
  40334. const children = object.children;
  40335. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40336. intersect( children[ i ], raycaster, intersects, true );
  40337. }
  40338. }
  40339. }
  40340. /**
  40341. * This class is an alternative to {@link Clock} with a different API design and behavior.
  40342. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  40343. *
  40344. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  40345. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  40346. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  40347. * is inactive (e.g. tab switched or browser hidden).
  40348. *
  40349. * ```js
  40350. * const timer = new Timer();
  40351. * timer.connect( document ); // use Page Visibility API
  40352. * ```
  40353. */
  40354. class Timer {
  40355. /**
  40356. * Constructs a new timer.
  40357. */
  40358. constructor() {
  40359. this._previousTime = 0;
  40360. this._currentTime = 0;
  40361. this._startTime = performance.now();
  40362. this._delta = 0;
  40363. this._elapsed = 0;
  40364. this._timescale = 1;
  40365. this._document = null;
  40366. this._pageVisibilityHandler = null;
  40367. }
  40368. /**
  40369. * Connect the timer to the given document.Calling this method is not mandatory to
  40370. * use the timer but enables the usage of the Page Visibility API to avoid large time
  40371. * delta values.
  40372. *
  40373. * @param {Document} document - The document.
  40374. */
  40375. connect( document ) {
  40376. this._document = document;
  40377. // use Page Visibility API to avoid large time delta values
  40378. if ( document.hidden !== undefined ) {
  40379. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  40380. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  40381. }
  40382. }
  40383. /**
  40384. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  40385. */
  40386. disconnect() {
  40387. if ( this._pageVisibilityHandler !== null ) {
  40388. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  40389. this._pageVisibilityHandler = null;
  40390. }
  40391. this._document = null;
  40392. }
  40393. /**
  40394. * Returns the time delta in seconds.
  40395. *
  40396. * @return {number} The time delta in second.
  40397. */
  40398. getDelta() {
  40399. return this._delta / 1000;
  40400. }
  40401. /**
  40402. * Returns the elapsed time in seconds.
  40403. *
  40404. * @return {number} The elapsed time in second.
  40405. */
  40406. getElapsed() {
  40407. return this._elapsed / 1000;
  40408. }
  40409. /**
  40410. * Returns the timescale.
  40411. *
  40412. * @return {number} The timescale.
  40413. */
  40414. getTimescale() {
  40415. return this._timescale;
  40416. }
  40417. /**
  40418. * Sets the given timescale which scale the time delta computation
  40419. * in `update()`.
  40420. *
  40421. * @param {number} timescale - The timescale to set.
  40422. * @return {Timer} A reference to this timer.
  40423. */
  40424. setTimescale( timescale ) {
  40425. this._timescale = timescale;
  40426. return this;
  40427. }
  40428. /**
  40429. * Resets the time computation for the current simulation step.
  40430. *
  40431. * @return {Timer} A reference to this timer.
  40432. */
  40433. reset() {
  40434. this._currentTime = performance.now() - this._startTime;
  40435. return this;
  40436. }
  40437. /**
  40438. * Can be used to free all internal resources. Usually called when
  40439. * the timer instance isn't required anymore.
  40440. */
  40441. dispose() {
  40442. this.disconnect();
  40443. }
  40444. /**
  40445. * Updates the internal state of the timer. This method should be called
  40446. * once per simulation step and before you perform queries against the timer
  40447. * (e.g. via `getDelta()`).
  40448. *
  40449. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  40450. * from the `requestAnimationFrame` callback argument. If not provided, the current
  40451. * time will be determined with `performance.now`.
  40452. * @return {Timer} A reference to this timer.
  40453. */
  40454. update( timestamp ) {
  40455. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  40456. this._delta = 0;
  40457. } else {
  40458. this._previousTime = this._currentTime;
  40459. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  40460. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  40461. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  40462. }
  40463. return this;
  40464. }
  40465. }
  40466. function handleVisibilityChange() {
  40467. if ( this._document.hidden === false ) this.reset();
  40468. }
  40469. /**
  40470. * This class can be used to represent points in 3D space as
  40471. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40472. */
  40473. class Spherical {
  40474. /**
  40475. * Constructs a new spherical.
  40476. *
  40477. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40478. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40479. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40480. */
  40481. constructor( radius = 1, phi = 0, theta = 0 ) {
  40482. /**
  40483. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40484. *
  40485. * @type {number}
  40486. * @default 1
  40487. */
  40488. this.radius = radius;
  40489. /**
  40490. * The polar angle in radians from the y (up) axis.
  40491. *
  40492. * @type {number}
  40493. * @default 0
  40494. */
  40495. this.phi = phi;
  40496. /**
  40497. * The equator/azimuthal angle in radians around the y (up) axis.
  40498. *
  40499. * @type {number}
  40500. * @default 0
  40501. */
  40502. this.theta = theta;
  40503. }
  40504. /**
  40505. * Sets the spherical components by copying the given values.
  40506. *
  40507. * @param {number} radius - The radius.
  40508. * @param {number} phi - The polar angle.
  40509. * @param {number} theta - The azimuthal angle.
  40510. * @return {Spherical} A reference to this spherical.
  40511. */
  40512. set( radius, phi, theta ) {
  40513. this.radius = radius;
  40514. this.phi = phi;
  40515. this.theta = theta;
  40516. return this;
  40517. }
  40518. /**
  40519. * Copies the values of the given spherical to this instance.
  40520. *
  40521. * @param {Spherical} other - The spherical to copy.
  40522. * @return {Spherical} A reference to this spherical.
  40523. */
  40524. copy( other ) {
  40525. this.radius = other.radius;
  40526. this.phi = other.phi;
  40527. this.theta = other.theta;
  40528. return this;
  40529. }
  40530. /**
  40531. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40532. * `0.000001`.
  40533. *
  40534. * @return {Spherical} A reference to this spherical.
  40535. */
  40536. makeSafe() {
  40537. const EPS = 0.000001;
  40538. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40539. return this;
  40540. }
  40541. /**
  40542. * Sets the spherical components from the given vector which is assumed to hold
  40543. * Cartesian coordinates.
  40544. *
  40545. * @param {Vector3} v - The vector to set.
  40546. * @return {Spherical} A reference to this spherical.
  40547. */
  40548. setFromVector3( v ) {
  40549. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40550. }
  40551. /**
  40552. * Sets the spherical components from the given Cartesian coordinates.
  40553. *
  40554. * @param {number} x - The x value.
  40555. * @param {number} y - The y value.
  40556. * @param {number} z - The z value.
  40557. * @return {Spherical} A reference to this spherical.
  40558. */
  40559. setFromCartesianCoords( x, y, z ) {
  40560. this.radius = Math.sqrt( x * x + y * y + z * z );
  40561. if ( this.radius === 0 ) {
  40562. this.theta = 0;
  40563. this.phi = 0;
  40564. } else {
  40565. this.theta = Math.atan2( x, z );
  40566. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40567. }
  40568. return this;
  40569. }
  40570. /**
  40571. * Returns a new spherical with copied values from this instance.
  40572. *
  40573. * @return {Spherical} A clone of this instance.
  40574. */
  40575. clone() {
  40576. return new this.constructor().copy( this );
  40577. }
  40578. }
  40579. /**
  40580. * This class can be used to represent points in 3D space as
  40581. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40582. */
  40583. class Cylindrical {
  40584. /**
  40585. * Constructs a new cylindrical.
  40586. *
  40587. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40588. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40589. * @param {number} [y=0] - The height above the x-z plane.
  40590. */
  40591. constructor( radius = 1, theta = 0, y = 0 ) {
  40592. /**
  40593. * The distance from the origin to a point in the x-z plane.
  40594. *
  40595. * @type {number}
  40596. * @default 1
  40597. */
  40598. this.radius = radius;
  40599. /**
  40600. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40601. *
  40602. * @type {number}
  40603. * @default 0
  40604. */
  40605. this.theta = theta;
  40606. /**
  40607. * The height above the x-z plane.
  40608. *
  40609. * @type {number}
  40610. * @default 0
  40611. */
  40612. this.y = y;
  40613. }
  40614. /**
  40615. * Sets the cylindrical components by copying the given values.
  40616. *
  40617. * @param {number} radius - The radius.
  40618. * @param {number} theta - The theta angle.
  40619. * @param {number} y - The height value.
  40620. * @return {Cylindrical} A reference to this cylindrical.
  40621. */
  40622. set( radius, theta, y ) {
  40623. this.radius = radius;
  40624. this.theta = theta;
  40625. this.y = y;
  40626. return this;
  40627. }
  40628. /**
  40629. * Copies the values of the given cylindrical to this instance.
  40630. *
  40631. * @param {Cylindrical} other - The cylindrical to copy.
  40632. * @return {Cylindrical} A reference to this cylindrical.
  40633. */
  40634. copy( other ) {
  40635. this.radius = other.radius;
  40636. this.theta = other.theta;
  40637. this.y = other.y;
  40638. return this;
  40639. }
  40640. /**
  40641. * Sets the cylindrical components from the given vector which is assumed to hold
  40642. * Cartesian coordinates.
  40643. *
  40644. * @param {Vector3} v - The vector to set.
  40645. * @return {Cylindrical} A reference to this cylindrical.
  40646. */
  40647. setFromVector3( v ) {
  40648. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40649. }
  40650. /**
  40651. * Sets the cylindrical components from the given Cartesian coordinates.
  40652. *
  40653. * @param {number} x - The x value.
  40654. * @param {number} y - The x value.
  40655. * @param {number} z - The x value.
  40656. * @return {Cylindrical} A reference to this cylindrical.
  40657. */
  40658. setFromCartesianCoords( x, y, z ) {
  40659. this.radius = Math.sqrt( x * x + z * z );
  40660. this.theta = Math.atan2( x, z );
  40661. this.y = y;
  40662. return this;
  40663. }
  40664. /**
  40665. * Returns a new cylindrical with copied values from this instance.
  40666. *
  40667. * @return {Cylindrical} A clone of this instance.
  40668. */
  40669. clone() {
  40670. return new this.constructor().copy( this );
  40671. }
  40672. }
  40673. /**
  40674. * Represents a 2x2 matrix.
  40675. *
  40676. * A Note on Row-Major and Column-Major Ordering:
  40677. *
  40678. * The constructor and {@link Matrix2#set} method take arguments in
  40679. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40680. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40681. * This means that calling:
  40682. * ```js
  40683. * const m = new THREE.Matrix2();
  40684. * m.set( 11, 12,
  40685. * 21, 22 );
  40686. * ```
  40687. * will result in the elements array containing:
  40688. * ```js
  40689. * m.elements = [ 11, 21,
  40690. * 12, 22 ];
  40691. * ```
  40692. * and internally all calculations are performed using column-major ordering.
  40693. * However, as the actual ordering makes no difference mathematically and
  40694. * most people are used to thinking about matrices in row-major order, the
  40695. * three.js documentation shows matrices in row-major order. Just bear in
  40696. * mind that if you are reading the source code, you'll have to take the
  40697. * transpose of any matrices outlined here to make sense of the calculations.
  40698. */
  40699. class Matrix2 {
  40700. /**
  40701. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40702. * in row-major order. If no arguments are provided, the constructor
  40703. * initializes the matrix as an identity matrix.
  40704. *
  40705. * @param {number} [n11] - 1-1 matrix element.
  40706. * @param {number} [n12] - 1-2 matrix element.
  40707. * @param {number} [n21] - 2-1 matrix element.
  40708. * @param {number} [n22] - 2-2 matrix element.
  40709. */
  40710. constructor( n11, n12, n21, n22 ) {
  40711. /**
  40712. * This flag can be used for type testing.
  40713. *
  40714. * @type {boolean}
  40715. * @readonly
  40716. * @default true
  40717. */
  40718. Matrix2.prototype.isMatrix2 = true;
  40719. /**
  40720. * A column-major list of matrix values.
  40721. *
  40722. * @type {Array<number>}
  40723. */
  40724. this.elements = [
  40725. 1, 0,
  40726. 0, 1,
  40727. ];
  40728. if ( n11 !== undefined ) {
  40729. this.set( n11, n12, n21, n22 );
  40730. }
  40731. }
  40732. /**
  40733. * Sets this matrix to the 2x2 identity matrix.
  40734. *
  40735. * @return {Matrix2} A reference to this matrix.
  40736. */
  40737. identity() {
  40738. this.set(
  40739. 1, 0,
  40740. 0, 1,
  40741. );
  40742. return this;
  40743. }
  40744. /**
  40745. * Sets the elements of the matrix from the given array.
  40746. *
  40747. * @param {Array<number>} array - The matrix elements in column-major order.
  40748. * @param {number} [offset=0] - Index of the first element in the array.
  40749. * @return {Matrix2} A reference to this matrix.
  40750. */
  40751. fromArray( array, offset = 0 ) {
  40752. for ( let i = 0; i < 4; i ++ ) {
  40753. this.elements[ i ] = array[ i + offset ];
  40754. }
  40755. return this;
  40756. }
  40757. /**
  40758. * Sets the elements of the matrix.The arguments are supposed to be
  40759. * in row-major order.
  40760. *
  40761. * @param {number} n11 - 1-1 matrix element.
  40762. * @param {number} n12 - 1-2 matrix element.
  40763. * @param {number} n21 - 2-1 matrix element.
  40764. * @param {number} n22 - 2-2 matrix element.
  40765. * @return {Matrix2} A reference to this matrix.
  40766. */
  40767. set( n11, n12, n21, n22 ) {
  40768. const te = this.elements;
  40769. te[ 0 ] = n11; te[ 2 ] = n12;
  40770. te[ 1 ] = n21; te[ 3 ] = n22;
  40771. return this;
  40772. }
  40773. }
  40774. const _vector$4 = /*@__PURE__*/ new Vector2();
  40775. /**
  40776. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40777. */
  40778. class Box2 {
  40779. /**
  40780. * Constructs a new bounding box.
  40781. *
  40782. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40783. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40784. */
  40785. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40786. /**
  40787. * This flag can be used for type testing.
  40788. *
  40789. * @type {boolean}
  40790. * @readonly
  40791. * @default true
  40792. */
  40793. this.isBox2 = true;
  40794. /**
  40795. * The lower boundary of the box.
  40796. *
  40797. * @type {Vector2}
  40798. */
  40799. this.min = min;
  40800. /**
  40801. * The upper boundary of the box.
  40802. *
  40803. * @type {Vector2}
  40804. */
  40805. this.max = max;
  40806. }
  40807. /**
  40808. * Sets the lower and upper boundaries of this box.
  40809. * Please note that this method only copies the values from the given objects.
  40810. *
  40811. * @param {Vector2} min - The lower boundary of the box.
  40812. * @param {Vector2} max - The upper boundary of the box.
  40813. * @return {Box2} A reference to this bounding box.
  40814. */
  40815. set( min, max ) {
  40816. this.min.copy( min );
  40817. this.max.copy( max );
  40818. return this;
  40819. }
  40820. /**
  40821. * Sets the upper and lower bounds of this box so it encloses the position data
  40822. * in the given array.
  40823. *
  40824. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40825. * @return {Box2} A reference to this bounding box.
  40826. */
  40827. setFromPoints( points ) {
  40828. this.makeEmpty();
  40829. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40830. this.expandByPoint( points[ i ] );
  40831. }
  40832. return this;
  40833. }
  40834. /**
  40835. * Centers this box on the given center vector and sets this box's width, height and
  40836. * depth to the given size values.
  40837. *
  40838. * @param {Vector2} center - The center of the box.
  40839. * @param {Vector2} size - The x and y dimensions of the box.
  40840. * @return {Box2} A reference to this bounding box.
  40841. */
  40842. setFromCenterAndSize( center, size ) {
  40843. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40844. this.min.copy( center ).sub( halfSize );
  40845. this.max.copy( center ).add( halfSize );
  40846. return this;
  40847. }
  40848. /**
  40849. * Returns a new box with copied values from this instance.
  40850. *
  40851. * @return {Box2} A clone of this instance.
  40852. */
  40853. clone() {
  40854. return new this.constructor().copy( this );
  40855. }
  40856. /**
  40857. * Copies the values of the given box to this instance.
  40858. *
  40859. * @param {Box2} box - The box to copy.
  40860. * @return {Box2} A reference to this bounding box.
  40861. */
  40862. copy( box ) {
  40863. this.min.copy( box.min );
  40864. this.max.copy( box.max );
  40865. return this;
  40866. }
  40867. /**
  40868. * Makes this box empty which means in encloses a zero space in 2D.
  40869. *
  40870. * @return {Box2} A reference to this bounding box.
  40871. */
  40872. makeEmpty() {
  40873. this.min.x = this.min.y = + Infinity;
  40874. this.max.x = this.max.y = - Infinity;
  40875. return this;
  40876. }
  40877. /**
  40878. * Returns true if this box includes zero points within its bounds.
  40879. * Note that a box with equal lower and upper bounds still includes one
  40880. * point, the one both bounds share.
  40881. *
  40882. * @return {boolean} Whether this box is empty or not.
  40883. */
  40884. isEmpty() {
  40885. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40886. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40887. }
  40888. /**
  40889. * Returns the center point of this box.
  40890. *
  40891. * @param {Vector2} target - The target vector that is used to store the method's result.
  40892. * @return {Vector2} The center point.
  40893. */
  40894. getCenter( target ) {
  40895. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40896. }
  40897. /**
  40898. * Returns the dimensions of this box.
  40899. *
  40900. * @param {Vector2} target - The target vector that is used to store the method's result.
  40901. * @return {Vector2} The size.
  40902. */
  40903. getSize( target ) {
  40904. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40905. }
  40906. /**
  40907. * Expands the boundaries of this box to include the given point.
  40908. *
  40909. * @param {Vector2} point - The point that should be included by the bounding box.
  40910. * @return {Box2} A reference to this bounding box.
  40911. */
  40912. expandByPoint( point ) {
  40913. this.min.min( point );
  40914. this.max.max( point );
  40915. return this;
  40916. }
  40917. /**
  40918. * Expands this box equilaterally by the given vector. The width of this
  40919. * box will be expanded by the x component of the vector in both
  40920. * directions. The height of this box will be expanded by the y component of
  40921. * the vector in both directions.
  40922. *
  40923. * @param {Vector2} vector - The vector that should expand the bounding box.
  40924. * @return {Box2} A reference to this bounding box.
  40925. */
  40926. expandByVector( vector ) {
  40927. this.min.sub( vector );
  40928. this.max.add( vector );
  40929. return this;
  40930. }
  40931. /**
  40932. * Expands each dimension of the box by the given scalar. If negative, the
  40933. * dimensions of the box will be contracted.
  40934. *
  40935. * @param {number} scalar - The scalar value that should expand the bounding box.
  40936. * @return {Box2} A reference to this bounding box.
  40937. */
  40938. expandByScalar( scalar ) {
  40939. this.min.addScalar( - scalar );
  40940. this.max.addScalar( scalar );
  40941. return this;
  40942. }
  40943. /**
  40944. * Returns `true` if the given point lies within or on the boundaries of this box.
  40945. *
  40946. * @param {Vector2} point - The point to test.
  40947. * @return {boolean} Whether the bounding box contains the given point or not.
  40948. */
  40949. containsPoint( point ) {
  40950. return point.x >= this.min.x && point.x <= this.max.x &&
  40951. point.y >= this.min.y && point.y <= this.max.y;
  40952. }
  40953. /**
  40954. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40955. * If this box and the given one are identical, this function also returns `true`.
  40956. *
  40957. * @param {Box2} box - The bounding box to test.
  40958. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40959. */
  40960. containsBox( box ) {
  40961. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40962. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40963. }
  40964. /**
  40965. * Returns a point as a proportion of this box's width and height.
  40966. *
  40967. * @param {Vector2} point - A point in 2D space.
  40968. * @param {Vector2} target - The target vector that is used to store the method's result.
  40969. * @return {Vector2} A point as a proportion of this box's width and height.
  40970. */
  40971. getParameter( point, target ) {
  40972. // This can potentially have a divide by zero if the box
  40973. // has a size dimension of 0.
  40974. return target.set(
  40975. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40976. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40977. );
  40978. }
  40979. /**
  40980. * Returns `true` if the given bounding box intersects with this bounding box.
  40981. *
  40982. * @param {Box2} box - The bounding box to test.
  40983. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40984. */
  40985. intersectsBox( box ) {
  40986. // using 4 splitting planes to rule out intersections
  40987. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40988. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40989. }
  40990. /**
  40991. * Clamps the given point within the bounds of this box.
  40992. *
  40993. * @param {Vector2} point - The point to clamp.
  40994. * @param {Vector2} target - The target vector that is used to store the method's result.
  40995. * @return {Vector2} The clamped point.
  40996. */
  40997. clampPoint( point, target ) {
  40998. return target.copy( point ).clamp( this.min, this.max );
  40999. }
  41000. /**
  41001. * Returns the euclidean distance from any edge of this box to the specified point. If
  41002. * the given point lies inside of this box, the distance will be `0`.
  41003. *
  41004. * @param {Vector2} point - The point to compute the distance to.
  41005. * @return {number} The euclidean distance.
  41006. */
  41007. distanceToPoint( point ) {
  41008. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  41009. }
  41010. /**
  41011. * Computes the intersection of this bounding box and the given one, setting the upper
  41012. * bound of this box to the lesser of the two boxes' upper bounds and the
  41013. * lower bound of this box to the greater of the two boxes' lower bounds. If
  41014. * there's no overlap, makes this box empty.
  41015. *
  41016. * @param {Box2} box - The bounding box to intersect with.
  41017. * @return {Box2} A reference to this bounding box.
  41018. */
  41019. intersect( box ) {
  41020. this.min.max( box.min );
  41021. this.max.min( box.max );
  41022. if ( this.isEmpty() ) this.makeEmpty();
  41023. return this;
  41024. }
  41025. /**
  41026. * Computes the union of this box and another and the given one, setting the upper
  41027. * bound of this box to the greater of the two boxes' upper bounds and the
  41028. * lower bound of this box to the lesser of the two boxes' lower bounds.
  41029. *
  41030. * @param {Box2} box - The bounding box that will be unioned with this instance.
  41031. * @return {Box2} A reference to this bounding box.
  41032. */
  41033. union( box ) {
  41034. this.min.min( box.min );
  41035. this.max.max( box.max );
  41036. return this;
  41037. }
  41038. /**
  41039. * Adds the given offset to both the upper and lower bounds of this bounding box,
  41040. * effectively moving it in 2D space.
  41041. *
  41042. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  41043. * @return {Box2} A reference to this bounding box.
  41044. */
  41045. translate( offset ) {
  41046. this.min.add( offset );
  41047. this.max.add( offset );
  41048. return this;
  41049. }
  41050. /**
  41051. * Returns `true` if this bounding box is equal with the given one.
  41052. *
  41053. * @param {Box2} box - The box to test for equality.
  41054. * @return {boolean} Whether this bounding box is equal with the given one.
  41055. */
  41056. equals( box ) {
  41057. return box.min.equals( this.min ) && box.max.equals( this.max );
  41058. }
  41059. }
  41060. const _startP = /*@__PURE__*/ new Vector3();
  41061. const _startEnd = /*@__PURE__*/ new Vector3();
  41062. const _d1 = /*@__PURE__*/ new Vector3();
  41063. const _d2 = /*@__PURE__*/ new Vector3();
  41064. const _r = /*@__PURE__*/ new Vector3();
  41065. const _c1 = /*@__PURE__*/ new Vector3();
  41066. const _c2 = /*@__PURE__*/ new Vector3();
  41067. /**
  41068. * An analytical line segment in 3D space represented by a start and end point.
  41069. */
  41070. class Line3 {
  41071. /**
  41072. * Constructs a new line segment.
  41073. *
  41074. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  41075. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  41076. */
  41077. constructor( start = new Vector3(), end = new Vector3() ) {
  41078. /**
  41079. * Start of the line segment.
  41080. *
  41081. * @type {Vector3}
  41082. */
  41083. this.start = start;
  41084. /**
  41085. * End of the line segment.
  41086. *
  41087. * @type {Vector3}
  41088. */
  41089. this.end = end;
  41090. }
  41091. /**
  41092. * Sets the start and end values by copying the given vectors.
  41093. *
  41094. * @param {Vector3} start - The start point.
  41095. * @param {Vector3} end - The end point.
  41096. * @return {Line3} A reference to this line segment.
  41097. */
  41098. set( start, end ) {
  41099. this.start.copy( start );
  41100. this.end.copy( end );
  41101. return this;
  41102. }
  41103. /**
  41104. * Copies the values of the given line segment to this instance.
  41105. *
  41106. * @param {Line3} line - The line segment to copy.
  41107. * @return {Line3} A reference to this line segment.
  41108. */
  41109. copy( line ) {
  41110. this.start.copy( line.start );
  41111. this.end.copy( line.end );
  41112. return this;
  41113. }
  41114. /**
  41115. * Returns the center of the line segment.
  41116. *
  41117. * @param {Vector3} target - The target vector that is used to store the method's result.
  41118. * @return {Vector3} The center point.
  41119. */
  41120. getCenter( target ) {
  41121. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  41122. }
  41123. /**
  41124. * Returns the delta vector of the line segment's start and end point.
  41125. *
  41126. * @param {Vector3} target - The target vector that is used to store the method's result.
  41127. * @return {Vector3} The delta vector.
  41128. */
  41129. delta( target ) {
  41130. return target.subVectors( this.end, this.start );
  41131. }
  41132. /**
  41133. * Returns the squared Euclidean distance between the line' start and end point.
  41134. *
  41135. * @return {number} The squared Euclidean distance.
  41136. */
  41137. distanceSq() {
  41138. return this.start.distanceToSquared( this.end );
  41139. }
  41140. /**
  41141. * Returns the Euclidean distance between the line' start and end point.
  41142. *
  41143. * @return {number} The Euclidean distance.
  41144. */
  41145. distance() {
  41146. return this.start.distanceTo( this.end );
  41147. }
  41148. /**
  41149. * Returns a vector at a certain position along the line segment.
  41150. *
  41151. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  41152. * @param {Vector3} target - The target vector that is used to store the method's result.
  41153. * @return {Vector3} The delta vector.
  41154. */
  41155. at( t, target ) {
  41156. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41157. }
  41158. /**
  41159. * Returns a point parameter based on the closest point as projected on the line segment.
  41160. *
  41161. * @param {Vector3} point - The point for which to return a point parameter.
  41162. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41163. * @return {number} The point parameter.
  41164. */
  41165. closestPointToPointParameter( point, clampToLine ) {
  41166. _startP.subVectors( point, this.start );
  41167. _startEnd.subVectors( this.end, this.start );
  41168. const startEnd2 = _startEnd.dot( _startEnd );
  41169. const startEnd_startP = _startEnd.dot( _startP );
  41170. let t = startEnd_startP / startEnd2;
  41171. if ( clampToLine ) {
  41172. t = clamp( t, 0, 1 );
  41173. }
  41174. return t;
  41175. }
  41176. /**
  41177. * Returns the closest point on the line for a given point.
  41178. *
  41179. * @param {Vector3} point - The point to compute the closest point on the line for.
  41180. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41181. * @param {Vector3} target - The target vector that is used to store the method's result.
  41182. * @return {Vector3} The closest point on the line.
  41183. */
  41184. closestPointToPoint( point, clampToLine, target ) {
  41185. const t = this.closestPointToPointParameter( point, clampToLine );
  41186. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41187. }
  41188. /**
  41189. * Returns the closest squared distance between this line segment and the given one.
  41190. *
  41191. * @param {Line3} line - The line segment to compute the closest squared distance to.
  41192. * @param {Vector3} [c1] - The closest point on this line segment.
  41193. * @param {Vector3} [c2] - The closest point on the given line segment.
  41194. * @return {number} The squared distance between this line segment and the given one.
  41195. */
  41196. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  41197. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  41198. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  41199. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  41200. // distance between between S1(s) and S2(t)
  41201. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  41202. let s, t;
  41203. const p1 = this.start;
  41204. const p2 = line.start;
  41205. const q1 = this.end;
  41206. const q2 = line.end;
  41207. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  41208. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  41209. _r.subVectors( p1, p2 );
  41210. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  41211. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  41212. const f = _d2.dot( _r );
  41213. // Check if either or both segments degenerate into points
  41214. if ( a <= EPSILON && e <= EPSILON ) {
  41215. // Both segments degenerate into points
  41216. c1.copy( p1 );
  41217. c2.copy( p2 );
  41218. c1.sub( c2 );
  41219. return c1.dot( c1 );
  41220. }
  41221. if ( a <= EPSILON ) {
  41222. // First segment degenerates into a point
  41223. s = 0;
  41224. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  41225. t = clamp( t, 0, 1 );
  41226. } else {
  41227. const c = _d1.dot( _r );
  41228. if ( e <= EPSILON ) {
  41229. // Second segment degenerates into a point
  41230. t = 0;
  41231. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  41232. } else {
  41233. // The general nondegenerate case starts here
  41234. const b = _d1.dot( _d2 );
  41235. const denom = a * e - b * b; // Always nonnegative
  41236. // If segments not parallel, compute closest point on L1 to L2 and
  41237. // clamp to segment S1. Else pick arbitrary s (here 0)
  41238. if ( denom !== 0 ) {
  41239. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  41240. } else {
  41241. s = 0;
  41242. }
  41243. // Compute point on L2 closest to S1(s) using
  41244. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  41245. t = ( b * s + f ) / e;
  41246. // If t in [0,1] done. Else clamp t, recompute s for the new value
  41247. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  41248. // and clamp s to [0, 1]
  41249. if ( t < 0 ) {
  41250. t = 0.;
  41251. s = clamp( - c / a, 0, 1 );
  41252. } else if ( t > 1 ) {
  41253. t = 1;
  41254. s = clamp( ( b - c ) / a, 0, 1 );
  41255. }
  41256. }
  41257. }
  41258. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  41259. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  41260. c1.sub( c2 );
  41261. return c1.dot( c1 );
  41262. }
  41263. /**
  41264. * Applies a 4x4 transformation matrix to this line segment.
  41265. *
  41266. * @param {Matrix4} matrix - The transformation matrix.
  41267. * @return {Line3} A reference to this line segment.
  41268. */
  41269. applyMatrix4( matrix ) {
  41270. this.start.applyMatrix4( matrix );
  41271. this.end.applyMatrix4( matrix );
  41272. return this;
  41273. }
  41274. /**
  41275. * Returns `true` if this line segment is equal with the given one.
  41276. *
  41277. * @param {Line3} line - The line segment to test for equality.
  41278. * @return {boolean} Whether this line segment is equal with the given one.
  41279. */
  41280. equals( line ) {
  41281. return line.start.equals( this.start ) && line.end.equals( this.end );
  41282. }
  41283. /**
  41284. * Returns a new line segment with copied values from this instance.
  41285. *
  41286. * @return {Line3} A clone of this instance.
  41287. */
  41288. clone() {
  41289. return new this.constructor().copy( this );
  41290. }
  41291. }
  41292. const _vector$3 = /*@__PURE__*/ new Vector3();
  41293. /**
  41294. * This displays a cone shaped helper object for a {@link SpotLight}.
  41295. *
  41296. * When the spot light or its target are transformed or light properties are
  41297. * changed, it's necessary to call the `update()` method of the respective helper.
  41298. *
  41299. * ```js
  41300. * const spotLight = new THREE.SpotLight( 0xffffff );
  41301. * spotLight.position.set( 10, 10, 10 );
  41302. * scene.add( spotLight );
  41303. *
  41304. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  41305. * scene.add( spotLightHelper );
  41306. * ```
  41307. *
  41308. * @augments Object3D
  41309. */
  41310. class SpotLightHelper extends Object3D {
  41311. /**
  41312. * Constructs a new spot light helper.
  41313. *
  41314. * @param {HemisphereLight} light - The light to be visualized.
  41315. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41316. * the color of the light.
  41317. */
  41318. constructor( light, color ) {
  41319. super();
  41320. /**
  41321. * The light being visualized.
  41322. *
  41323. * @type {SpotLight}
  41324. */
  41325. this.light = light;
  41326. this.matrixAutoUpdate = false;
  41327. /**
  41328. * The color parameter passed in the constructor.
  41329. * If not set, the helper will take the color of the light.
  41330. *
  41331. * @type {number|Color|string}
  41332. */
  41333. this.color = color;
  41334. this.type = 'SpotLightHelper';
  41335. const geometry = new BufferGeometry();
  41336. const positions = [
  41337. 0, 0, 0, 0, 0, 1,
  41338. 0, 0, 0, 1, 0, 1,
  41339. 0, 0, 0, -1, 0, 1,
  41340. 0, 0, 0, 0, 1, 1,
  41341. 0, 0, 0, 0, -1, 1
  41342. ];
  41343. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  41344. const p1 = ( i / l ) * Math.PI * 2;
  41345. const p2 = ( j / l ) * Math.PI * 2;
  41346. positions.push(
  41347. Math.cos( p1 ), Math.sin( p1 ), 1,
  41348. Math.cos( p2 ), Math.sin( p2 ), 1
  41349. );
  41350. }
  41351. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41352. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41353. this.cone = new LineSegments( geometry, material );
  41354. this.add( this.cone );
  41355. this.update();
  41356. }
  41357. /**
  41358. * Frees the GPU-related resources allocated by this instance. Call this
  41359. * method whenever this instance is no longer used in your app.
  41360. */
  41361. dispose() {
  41362. this.cone.geometry.dispose();
  41363. this.cone.material.dispose();
  41364. }
  41365. /**
  41366. * Updates the helper to match the position and direction of the
  41367. * light being visualized.
  41368. */
  41369. update() {
  41370. this.light.updateWorldMatrix( true, false );
  41371. this.light.target.updateWorldMatrix( true, false );
  41372. // update the local matrix based on the parent and light target transforms
  41373. if ( this.parent ) {
  41374. this.parent.updateWorldMatrix( true );
  41375. this.matrix
  41376. .copy( this.parent.matrixWorld )
  41377. .invert()
  41378. .multiply( this.light.matrixWorld );
  41379. } else {
  41380. this.matrix.copy( this.light.matrixWorld );
  41381. }
  41382. this.matrixWorld.copy( this.light.matrixWorld );
  41383. const coneLength = this.light.distance ? this.light.distance : 1000;
  41384. const coneWidth = coneLength * Math.tan( this.light.angle );
  41385. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41386. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41387. this.cone.lookAt( _vector$3 );
  41388. if ( this.color !== undefined ) {
  41389. this.cone.material.color.set( this.color );
  41390. } else {
  41391. this.cone.material.color.copy( this.light.color );
  41392. }
  41393. }
  41394. }
  41395. const _vector$2 = /*@__PURE__*/ new Vector3();
  41396. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41397. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41398. /**
  41399. * A helper object to assist with visualizing a {@link Skeleton}.
  41400. *
  41401. * ```js
  41402. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41403. * scene.add( helper );
  41404. * ```
  41405. *
  41406. * @augments LineSegments
  41407. */
  41408. class SkeletonHelper extends LineSegments {
  41409. /**
  41410. * Constructs a new skeleton helper.
  41411. *
  41412. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41413. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41414. */
  41415. constructor( object ) {
  41416. const bones = getBoneList( object );
  41417. const geometry = new BufferGeometry();
  41418. const vertices = [];
  41419. const colors = [];
  41420. for ( let i = 0; i < bones.length; i ++ ) {
  41421. const bone = bones[ i ];
  41422. if ( bone.parent && bone.parent.isBone ) {
  41423. vertices.push( 0, 0, 0 );
  41424. vertices.push( 0, 0, 0 );
  41425. colors.push( 0, 0, 0 );
  41426. colors.push( 0, 0, 0 );
  41427. }
  41428. }
  41429. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41430. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41431. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41432. super( geometry, material );
  41433. /**
  41434. * This flag can be used for type testing.
  41435. *
  41436. * @type {boolean}
  41437. * @readonly
  41438. * @default true
  41439. */
  41440. this.isSkeletonHelper = true;
  41441. this.type = 'SkeletonHelper';
  41442. /**
  41443. * The object being visualized.
  41444. *
  41445. * @type {Object3D}
  41446. */
  41447. this.root = object;
  41448. /**
  41449. * The list of bones that the helper visualizes.
  41450. *
  41451. * @type {Array<Bone>}
  41452. */
  41453. this.bones = bones;
  41454. this.matrix = object.matrixWorld;
  41455. this.matrixAutoUpdate = false;
  41456. // colors
  41457. const color1 = new Color( 0x0000ff );
  41458. const color2 = new Color( 0x00ff00 );
  41459. this.setColors( color1, color2 );
  41460. }
  41461. updateMatrixWorld( force ) {
  41462. const bones = this.bones;
  41463. const geometry = this.geometry;
  41464. const position = geometry.getAttribute( 'position' );
  41465. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41466. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41467. const bone = bones[ i ];
  41468. if ( bone.parent && bone.parent.isBone ) {
  41469. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41470. _vector$2.setFromMatrixPosition( _boneMatrix );
  41471. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41472. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41473. _vector$2.setFromMatrixPosition( _boneMatrix );
  41474. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41475. j += 2;
  41476. }
  41477. }
  41478. geometry.getAttribute( 'position' ).needsUpdate = true;
  41479. super.updateMatrixWorld( force );
  41480. }
  41481. /**
  41482. * Defines the colors of the helper.
  41483. *
  41484. * @param {Color} color1 - The first line color for each bone.
  41485. * @param {Color} color2 - The second line color for each bone.
  41486. * @return {SkeletonHelper} A reference to this helper.
  41487. */
  41488. setColors( color1, color2 ) {
  41489. const geometry = this.geometry;
  41490. const colorAttribute = geometry.getAttribute( 'color' );
  41491. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41492. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41493. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41494. }
  41495. colorAttribute.needsUpdate = true;
  41496. return this;
  41497. }
  41498. /**
  41499. * Frees the GPU-related resources allocated by this instance. Call this
  41500. * method whenever this instance is no longer used in your app.
  41501. */
  41502. dispose() {
  41503. this.geometry.dispose();
  41504. this.material.dispose();
  41505. }
  41506. }
  41507. function getBoneList( object ) {
  41508. const boneList = [];
  41509. if ( object.isBone === true ) {
  41510. boneList.push( object );
  41511. }
  41512. for ( let i = 0; i < object.children.length; i ++ ) {
  41513. boneList.push( ...getBoneList( object.children[ i ] ) );
  41514. }
  41515. return boneList;
  41516. }
  41517. /**
  41518. * This displays a helper object consisting of a spherical mesh for
  41519. * visualizing an instance of {@link PointLight}.
  41520. *
  41521. * ```js
  41522. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41523. * pointLight.position.set( 10, 10, 10 );
  41524. * scene.add( pointLight );
  41525. *
  41526. * const sphereSize = 1;
  41527. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41528. * scene.add( pointLightHelper );
  41529. * ```
  41530. *
  41531. * @augments Mesh
  41532. */
  41533. class PointLightHelper extends Mesh {
  41534. /**
  41535. * Constructs a new point light helper.
  41536. *
  41537. * @param {PointLight} light - The light to be visualized.
  41538. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41539. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41540. * the color of the light.
  41541. */
  41542. constructor( light, sphereSize, color ) {
  41543. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41544. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41545. super( geometry, material );
  41546. /**
  41547. * The light being visualized.
  41548. *
  41549. * @type {PointLight}
  41550. */
  41551. this.light = light;
  41552. /**
  41553. * The color parameter passed in the constructor.
  41554. * If not set, the helper will take the color of the light.
  41555. *
  41556. * @type {number|Color|string}
  41557. */
  41558. this.color = color;
  41559. this.type = 'PointLightHelper';
  41560. this.matrix = this.light.matrixWorld;
  41561. this.matrixAutoUpdate = false;
  41562. this.update();
  41563. /*
  41564. // TODO: delete this comment?
  41565. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  41566. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  41567. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  41568. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  41569. const d = light.distance;
  41570. if ( d === 0.0 ) {
  41571. this.lightDistance.visible = false;
  41572. } else {
  41573. this.lightDistance.scale.set( d, d, d );
  41574. }
  41575. this.add( this.lightDistance );
  41576. */
  41577. }
  41578. /**
  41579. * Frees the GPU-related resources allocated by this instance. Call this
  41580. * method whenever this instance is no longer used in your app.
  41581. */
  41582. dispose() {
  41583. this.geometry.dispose();
  41584. this.material.dispose();
  41585. }
  41586. /**
  41587. * Updates the helper to match the position of the
  41588. * light being visualized.
  41589. */
  41590. update() {
  41591. this.light.updateWorldMatrix( true, false );
  41592. if ( this.color !== undefined ) {
  41593. this.material.color.set( this.color );
  41594. } else {
  41595. this.material.color.copy( this.light.color );
  41596. }
  41597. /*
  41598. const d = this.light.distance;
  41599. if ( d === 0.0 ) {
  41600. this.lightDistance.visible = false;
  41601. } else {
  41602. this.lightDistance.visible = true;
  41603. this.lightDistance.scale.set( d, d, d );
  41604. }
  41605. */
  41606. }
  41607. }
  41608. const _vector$1 = /*@__PURE__*/ new Vector3();
  41609. const _color1 = /*@__PURE__*/ new Color();
  41610. const _color2 = /*@__PURE__*/ new Color();
  41611. /**
  41612. * Creates a visual aid consisting of a spherical mesh for a
  41613. * given {@link HemisphereLight}.
  41614. *
  41615. * When the hemisphere light is transformed or its light properties are changed,
  41616. * it's necessary to call the `update()` method of the respective helper.
  41617. *
  41618. * ```js
  41619. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41620. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41621. * scene.add( helper );
  41622. * ```
  41623. *
  41624. * @augments Object3D
  41625. */
  41626. class HemisphereLightHelper extends Object3D {
  41627. /**
  41628. * Constructs a new hemisphere light helper.
  41629. *
  41630. * @param {HemisphereLight} light - The light to be visualized.
  41631. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41632. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41633. * the color of the light.
  41634. */
  41635. constructor( light, size, color ) {
  41636. super();
  41637. /**
  41638. * The light being visualized.
  41639. *
  41640. * @type {HemisphereLight}
  41641. */
  41642. this.light = light;
  41643. this.matrix = light.matrixWorld;
  41644. this.matrixAutoUpdate = false;
  41645. /**
  41646. * The color parameter passed in the constructor.
  41647. * If not set, the helper will take the color of the light.
  41648. *
  41649. * @type {number|Color|string}
  41650. */
  41651. this.color = color;
  41652. this.type = 'HemisphereLightHelper';
  41653. const geometry = new OctahedronGeometry( size );
  41654. geometry.rotateY( Math.PI * 0.5 );
  41655. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41656. if ( this.color === undefined ) this.material.vertexColors = true;
  41657. const position = geometry.getAttribute( 'position' );
  41658. const colors = new Float32Array( position.count * 3 );
  41659. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41660. this.add( new Mesh( geometry, this.material ) );
  41661. this.update();
  41662. }
  41663. /**
  41664. * Frees the GPU-related resources allocated by this instance. Call this
  41665. * method whenever this instance is no longer used in your app.
  41666. */
  41667. dispose() {
  41668. this.children[ 0 ].geometry.dispose();
  41669. this.children[ 0 ].material.dispose();
  41670. }
  41671. /**
  41672. * Updates the helper to match the position and direction of the
  41673. * light being visualized.
  41674. */
  41675. update() {
  41676. const mesh = this.children[ 0 ];
  41677. if ( this.color !== undefined ) {
  41678. this.material.color.set( this.color );
  41679. } else {
  41680. const colors = mesh.geometry.getAttribute( 'color' );
  41681. _color1.copy( this.light.color );
  41682. _color2.copy( this.light.groundColor );
  41683. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41684. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41685. colors.setXYZ( i, color.r, color.g, color.b );
  41686. }
  41687. colors.needsUpdate = true;
  41688. }
  41689. this.light.updateWorldMatrix( true, false );
  41690. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41691. }
  41692. }
  41693. /**
  41694. * The helper is an object to define grids. Grids are two-dimensional
  41695. * arrays of lines.
  41696. *
  41697. * ```js
  41698. * const size = 10;
  41699. * const divisions = 10;
  41700. *
  41701. * const gridHelper = new THREE.GridHelper( size, divisions );
  41702. * scene.add( gridHelper );
  41703. * ```
  41704. *
  41705. * @augments LineSegments
  41706. */
  41707. class GridHelper extends LineSegments {
  41708. /**
  41709. * Constructs a new grid helper.
  41710. *
  41711. * @param {number} [size=10] - The size of the grid.
  41712. * @param {number} [divisions=10] - The number of divisions across the grid.
  41713. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41714. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41715. */
  41716. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41717. color1 = new Color( color1 );
  41718. color2 = new Color( color2 );
  41719. const center = divisions / 2;
  41720. const step = size / divisions;
  41721. const halfSize = size / 2;
  41722. const vertices = [], colors = [];
  41723. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41724. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41725. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41726. const color = i === center ? color1 : color2;
  41727. color.toArray( colors, j ); j += 3;
  41728. color.toArray( colors, j ); j += 3;
  41729. color.toArray( colors, j ); j += 3;
  41730. color.toArray( colors, j ); j += 3;
  41731. }
  41732. const geometry = new BufferGeometry();
  41733. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41734. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41735. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41736. super( geometry, material );
  41737. this.type = 'GridHelper';
  41738. }
  41739. /**
  41740. * Frees the GPU-related resources allocated by this instance. Call this
  41741. * method whenever this instance is no longer used in your app.
  41742. */
  41743. dispose() {
  41744. this.geometry.dispose();
  41745. this.material.dispose();
  41746. }
  41747. }
  41748. /**
  41749. * This helper is an object to define polar grids. Grids are
  41750. * two-dimensional arrays of lines.
  41751. *
  41752. * ```js
  41753. * const radius = 10;
  41754. * const sectors = 16;
  41755. * const rings = 8;
  41756. * const divisions = 64;
  41757. *
  41758. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41759. * scene.add( helper );
  41760. * ```
  41761. *
  41762. * @augments LineSegments
  41763. */
  41764. class PolarGridHelper extends LineSegments {
  41765. /**
  41766. * Constructs a new polar grid helper.
  41767. *
  41768. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41769. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41770. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41771. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41772. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41773. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41774. */
  41775. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41776. color1 = new Color( color1 );
  41777. color2 = new Color( color2 );
  41778. const vertices = [];
  41779. const colors = [];
  41780. // create the sectors
  41781. if ( sectors > 1 ) {
  41782. for ( let i = 0; i < sectors; i ++ ) {
  41783. const v = ( i / sectors ) * ( Math.PI * 2 );
  41784. const x = Math.sin( v ) * radius;
  41785. const z = Math.cos( v ) * radius;
  41786. vertices.push( 0, 0, 0 );
  41787. vertices.push( x, 0, z );
  41788. const color = ( i & 1 ) ? color1 : color2;
  41789. colors.push( color.r, color.g, color.b );
  41790. colors.push( color.r, color.g, color.b );
  41791. }
  41792. }
  41793. // create the rings
  41794. for ( let i = 0; i < rings; i ++ ) {
  41795. const color = ( i & 1 ) ? color1 : color2;
  41796. const r = radius - ( radius / rings * i );
  41797. for ( let j = 0; j < divisions; j ++ ) {
  41798. // first vertex
  41799. let v = ( j / divisions ) * ( Math.PI * 2 );
  41800. let x = Math.sin( v ) * r;
  41801. let z = Math.cos( v ) * r;
  41802. vertices.push( x, 0, z );
  41803. colors.push( color.r, color.g, color.b );
  41804. // second vertex
  41805. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41806. x = Math.sin( v ) * r;
  41807. z = Math.cos( v ) * r;
  41808. vertices.push( x, 0, z );
  41809. colors.push( color.r, color.g, color.b );
  41810. }
  41811. }
  41812. const geometry = new BufferGeometry();
  41813. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41814. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41815. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41816. super( geometry, material );
  41817. this.type = 'PolarGridHelper';
  41818. }
  41819. /**
  41820. * Frees the GPU-related resources allocated by this instance. Call this
  41821. * method whenever this instance is no longer used in your app.
  41822. */
  41823. dispose() {
  41824. this.geometry.dispose();
  41825. this.material.dispose();
  41826. }
  41827. }
  41828. const _v1 = /*@__PURE__*/ new Vector3();
  41829. const _v2 = /*@__PURE__*/ new Vector3();
  41830. const _v3 = /*@__PURE__*/ new Vector3();
  41831. /**
  41832. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41833. * effect on the scene. This consists of a plane and a line representing the
  41834. * light's position and direction.
  41835. *
  41836. * When the directional light or its target are transformed or light properties
  41837. * are changed, it's necessary to call the `update()` method of the respective helper.
  41838. *
  41839. * ```js
  41840. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41841. * scene.add( light );
  41842. *
  41843. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41844. * scene.add( helper );
  41845. * ```
  41846. *
  41847. * @augments Object3D
  41848. */
  41849. class DirectionalLightHelper extends Object3D {
  41850. /**
  41851. * Constructs a new directional light helper.
  41852. *
  41853. * @param {DirectionalLight} light - The light to be visualized.
  41854. * @param {number} [size=1] - The dimensions of the plane.
  41855. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41856. * the color of the light.
  41857. */
  41858. constructor( light, size, color ) {
  41859. super();
  41860. /**
  41861. * The light being visualized.
  41862. *
  41863. * @type {DirectionalLight}
  41864. */
  41865. this.light = light;
  41866. this.matrix = light.matrixWorld;
  41867. this.matrixAutoUpdate = false;
  41868. /**
  41869. * The color parameter passed in the constructor.
  41870. * If not set, the helper will take the color of the light.
  41871. *
  41872. * @type {number|Color|string}
  41873. */
  41874. this.color = color;
  41875. this.type = 'DirectionalLightHelper';
  41876. if ( size === undefined ) size = 1;
  41877. let geometry = new BufferGeometry();
  41878. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41879. - size, size, 0,
  41880. size, size, 0,
  41881. size, - size, 0,
  41882. - size, - size, 0,
  41883. - size, size, 0
  41884. ], 3 ) );
  41885. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41886. /**
  41887. * Contains the line showing the location of the directional light.
  41888. *
  41889. * @type {Line}
  41890. */
  41891. this.lightPlane = new Line( geometry, material );
  41892. this.add( this.lightPlane );
  41893. geometry = new BufferGeometry();
  41894. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41895. /**
  41896. * Represents the target line of the directional light.
  41897. *
  41898. * @type {Line}
  41899. */
  41900. this.targetLine = new Line( geometry, material );
  41901. this.add( this.targetLine );
  41902. this.update();
  41903. }
  41904. /**
  41905. * Frees the GPU-related resources allocated by this instance. Call this
  41906. * method whenever this instance is no longer used in your app.
  41907. */
  41908. dispose() {
  41909. this.lightPlane.geometry.dispose();
  41910. this.lightPlane.material.dispose();
  41911. this.targetLine.geometry.dispose();
  41912. this.targetLine.material.dispose();
  41913. }
  41914. /**
  41915. * Updates the helper to match the position and direction of the
  41916. * light being visualized.
  41917. */
  41918. update() {
  41919. this.light.updateWorldMatrix( true, false );
  41920. this.light.target.updateWorldMatrix( true, false );
  41921. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41922. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41923. _v3.subVectors( _v2, _v1 );
  41924. this.lightPlane.lookAt( _v2 );
  41925. if ( this.color !== undefined ) {
  41926. this.lightPlane.material.color.set( this.color );
  41927. this.targetLine.material.color.set( this.color );
  41928. } else {
  41929. this.lightPlane.material.color.copy( this.light.color );
  41930. this.targetLine.material.color.copy( this.light.color );
  41931. }
  41932. this.targetLine.lookAt( _v2 );
  41933. this.targetLine.scale.z = _v3.length();
  41934. }
  41935. }
  41936. const _vector = /*@__PURE__*/ new Vector3();
  41937. const _camera = /*@__PURE__*/ new Camera();
  41938. /**
  41939. * This helps with visualizing what a camera contains in its frustum. It
  41940. * visualizes the frustum of a camera using a line segments.
  41941. *
  41942. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  41943. *
  41944. * `CameraHelper` must be a child of the scene.
  41945. *
  41946. * When the camera is transformed or its projection matrix is changed, it's necessary
  41947. * to call the `update()` method of the respective helper.
  41948. *
  41949. * ```js
  41950. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41951. * const helper = new THREE.CameraHelper( camera );
  41952. * scene.add( helper );
  41953. * ```
  41954. *
  41955. * @augments LineSegments
  41956. */
  41957. class CameraHelper extends LineSegments {
  41958. /**
  41959. * Constructs a new arrow helper.
  41960. *
  41961. * @param {Camera} camera - The camera to visualize.
  41962. */
  41963. constructor( camera ) {
  41964. const geometry = new BufferGeometry();
  41965. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41966. const vertices = [];
  41967. const colors = [];
  41968. const pointMap = {};
  41969. // near
  41970. addLine( 'n1', 'n2' );
  41971. addLine( 'n2', 'n4' );
  41972. addLine( 'n4', 'n3' );
  41973. addLine( 'n3', 'n1' );
  41974. // far
  41975. addLine( 'f1', 'f2' );
  41976. addLine( 'f2', 'f4' );
  41977. addLine( 'f4', 'f3' );
  41978. addLine( 'f3', 'f1' );
  41979. // sides
  41980. addLine( 'n1', 'f1' );
  41981. addLine( 'n2', 'f2' );
  41982. addLine( 'n3', 'f3' );
  41983. addLine( 'n4', 'f4' );
  41984. // cone
  41985. addLine( 'p', 'n1' );
  41986. addLine( 'p', 'n2' );
  41987. addLine( 'p', 'n3' );
  41988. addLine( 'p', 'n4' );
  41989. // up
  41990. addLine( 'u1', 'u2' );
  41991. addLine( 'u2', 'u3' );
  41992. addLine( 'u3', 'u1' );
  41993. // target
  41994. addLine( 'c', 't' );
  41995. addLine( 'p', 'c' );
  41996. // cross
  41997. addLine( 'cn1', 'cn2' );
  41998. addLine( 'cn3', 'cn4' );
  41999. addLine( 'cf1', 'cf2' );
  42000. addLine( 'cf3', 'cf4' );
  42001. function addLine( a, b ) {
  42002. addPoint( a );
  42003. addPoint( b );
  42004. }
  42005. function addPoint( id ) {
  42006. vertices.push( 0, 0, 0 );
  42007. colors.push( 0, 0, 0 );
  42008. if ( pointMap[ id ] === undefined ) {
  42009. pointMap[ id ] = [];
  42010. }
  42011. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  42012. }
  42013. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42014. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42015. super( geometry, material );
  42016. this.type = 'CameraHelper';
  42017. /**
  42018. * The camera being visualized.
  42019. *
  42020. * @type {Camera}
  42021. */
  42022. this.camera = camera;
  42023. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  42024. this.matrix = camera.matrixWorld;
  42025. this.matrixAutoUpdate = false;
  42026. /**
  42027. * This contains the points used to visualize the camera.
  42028. *
  42029. * @type {Object<string,Array<number>>}
  42030. */
  42031. this.pointMap = pointMap;
  42032. this.update();
  42033. // colors
  42034. const colorFrustum = new Color( 0xffaa00 );
  42035. const colorCone = new Color( 0xff0000 );
  42036. const colorUp = new Color( 0x00aaff );
  42037. const colorTarget = new Color( 0xffffff );
  42038. const colorCross = new Color( 0x333333 );
  42039. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  42040. }
  42041. /**
  42042. * Defines the colors of the helper.
  42043. *
  42044. * @param {Color} frustum - The frustum line color.
  42045. * @param {Color} cone - The cone line color.
  42046. * @param {Color} up - The up line color.
  42047. * @param {Color} target - The target line color.
  42048. * @param {Color} cross - The cross line color.
  42049. * @return {CameraHelper} A reference to this helper.
  42050. */
  42051. setColors( frustum, cone, up, target, cross ) {
  42052. const geometry = this.geometry;
  42053. const colorAttribute = geometry.getAttribute( 'color' );
  42054. // near
  42055. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  42056. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  42057. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  42058. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  42059. // far
  42060. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  42061. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  42062. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  42063. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  42064. // sides
  42065. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  42066. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  42067. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  42068. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  42069. // cone
  42070. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  42071. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  42072. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  42073. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  42074. // up
  42075. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  42076. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  42077. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  42078. // target
  42079. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  42080. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  42081. // cross
  42082. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  42083. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  42084. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  42085. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  42086. colorAttribute.needsUpdate = true;
  42087. return this;
  42088. }
  42089. /**
  42090. * Updates the helper based on the projection matrix of the camera.
  42091. */
  42092. update() {
  42093. const geometry = this.geometry;
  42094. const pointMap = this.pointMap;
  42095. const w = 1, h = 1;
  42096. let nearZ, farZ;
  42097. // we need just camera projection matrix inverse
  42098. // world matrix must be identity
  42099. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  42100. // Adjust z values based on coordinate system
  42101. if ( this.camera.reversedDepth === true ) {
  42102. nearZ = 1;
  42103. farZ = 0;
  42104. } else {
  42105. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  42106. nearZ = -1;
  42107. farZ = 1;
  42108. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  42109. nearZ = 0;
  42110. farZ = 1;
  42111. } else {
  42112. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  42113. }
  42114. }
  42115. // center / target
  42116. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  42117. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  42118. // near
  42119. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  42120. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  42121. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  42122. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  42123. // far
  42124. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  42125. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  42126. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  42127. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  42128. // up
  42129. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  42130. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  42131. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  42132. // cross
  42133. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  42134. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  42135. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  42136. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  42137. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  42138. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  42139. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  42140. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  42141. geometry.getAttribute( 'position' ).needsUpdate = true;
  42142. }
  42143. /**
  42144. * Frees the GPU-related resources allocated by this instance. Call this
  42145. * method whenever this instance is no longer used in your app.
  42146. */
  42147. dispose() {
  42148. this.geometry.dispose();
  42149. this.material.dispose();
  42150. }
  42151. }
  42152. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  42153. _vector.set( x, y, z ).unproject( camera );
  42154. const points = pointMap[ point ];
  42155. if ( points !== undefined ) {
  42156. const position = geometry.getAttribute( 'position' );
  42157. for ( let i = 0, l = points.length; i < l; i ++ ) {
  42158. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  42159. }
  42160. }
  42161. }
  42162. const _box = /*@__PURE__*/ new Box3();
  42163. /**
  42164. * Helper object to graphically show the world-axis-aligned bounding box
  42165. * around an object. The actual bounding box is handled with {@link Box3},
  42166. * this is just a visual helper for debugging. It can be automatically
  42167. * resized with {@link BoxHelper#update} when the object it's created from
  42168. * is transformed. Note that the object must have a geometry for this to work,
  42169. * so it won't work with sprites.
  42170. *
  42171. * ```js
  42172. * const sphere = new THREE.SphereGeometry();
  42173. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  42174. * const box = new THREE.BoxHelper( object, 0xffff00 );
  42175. * scene.add( box );
  42176. * ```
  42177. *
  42178. * @augments LineSegments
  42179. */
  42180. class BoxHelper extends LineSegments {
  42181. /**
  42182. * Constructs a new box helper.
  42183. *
  42184. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  42185. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42186. */
  42187. constructor( object, color = 0xffff00 ) {
  42188. 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 ] );
  42189. const positions = new Float32Array( 8 * 3 );
  42190. const geometry = new BufferGeometry();
  42191. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42192. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  42193. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42194. /**
  42195. * The 3D object being visualized.
  42196. *
  42197. * @type {Object3D}
  42198. */
  42199. this.object = object;
  42200. this.type = 'BoxHelper';
  42201. this.matrixAutoUpdate = false;
  42202. this.update();
  42203. }
  42204. /**
  42205. * Updates the helper's geometry to match the dimensions of the object,
  42206. * including any children.
  42207. */
  42208. update() {
  42209. if ( this.object !== undefined ) {
  42210. _box.setFromObject( this.object );
  42211. }
  42212. if ( _box.isEmpty() ) return;
  42213. const min = _box.min;
  42214. const max = _box.max;
  42215. /*
  42216. 5____4
  42217. 1/___0/|
  42218. | 6__|_7
  42219. 2/___3/
  42220. 0: max.x, max.y, max.z
  42221. 1: min.x, max.y, max.z
  42222. 2: min.x, min.y, max.z
  42223. 3: max.x, min.y, max.z
  42224. 4: max.x, max.y, min.z
  42225. 5: min.x, max.y, min.z
  42226. 6: min.x, min.y, min.z
  42227. 7: max.x, min.y, min.z
  42228. */
  42229. const position = this.geometry.attributes.position;
  42230. const array = position.array;
  42231. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  42232. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  42233. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  42234. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  42235. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  42236. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  42237. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  42238. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  42239. position.needsUpdate = true;
  42240. this.geometry.computeBoundingSphere();
  42241. }
  42242. /**
  42243. * Updates the wireframe box for the passed object.
  42244. *
  42245. * @param {Object3D} object - The 3D object to create the helper for.
  42246. * @return {BoxHelper} A reference to this instance.
  42247. */
  42248. setFromObject( object ) {
  42249. this.object = object;
  42250. this.update();
  42251. return this;
  42252. }
  42253. copy( source, recursive ) {
  42254. super.copy( source, recursive );
  42255. this.object = source.object;
  42256. return this;
  42257. }
  42258. /**
  42259. * Frees the GPU-related resources allocated by this instance. Call this
  42260. * method whenever this instance is no longer used in your app.
  42261. */
  42262. dispose() {
  42263. this.geometry.dispose();
  42264. this.material.dispose();
  42265. }
  42266. }
  42267. /**
  42268. * A helper object to visualize an instance of {@link Box3}.
  42269. *
  42270. * ```js
  42271. * const box = new THREE.Box3();
  42272. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  42273. *
  42274. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  42275. * scene.add( helper )
  42276. * ```
  42277. *
  42278. * @augments LineSegments
  42279. */
  42280. class Box3Helper extends LineSegments {
  42281. /**
  42282. * Constructs a new box3 helper.
  42283. *
  42284. * @param {Box3} box - The box to visualize.
  42285. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42286. */
  42287. constructor( box, color = 0xffff00 ) {
  42288. 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 ] );
  42289. 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 ];
  42290. const geometry = new BufferGeometry();
  42291. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42292. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42293. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42294. /**
  42295. * The box being visualized.
  42296. *
  42297. * @type {Box3}
  42298. */
  42299. this.box = box;
  42300. this.type = 'Box3Helper';
  42301. this.geometry.computeBoundingSphere();
  42302. }
  42303. updateMatrixWorld( force ) {
  42304. const box = this.box;
  42305. if ( box.isEmpty() ) return;
  42306. box.getCenter( this.position );
  42307. box.getSize( this.scale );
  42308. this.scale.multiplyScalar( 0.5 );
  42309. super.updateMatrixWorld( force );
  42310. }
  42311. /**
  42312. * Frees the GPU-related resources allocated by this instance. Call this
  42313. * method whenever this instance is no longer used in your app.
  42314. */
  42315. dispose() {
  42316. this.geometry.dispose();
  42317. this.material.dispose();
  42318. }
  42319. }
  42320. /**
  42321. * A helper object to visualize an instance of {@link Plane}.
  42322. *
  42323. * ```js
  42324. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  42325. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  42326. * scene.add( helper );
  42327. * ```
  42328. *
  42329. * @augments Line
  42330. */
  42331. class PlaneHelper extends Line {
  42332. /**
  42333. * Constructs a new plane helper.
  42334. *
  42335. * @param {Plane} plane - The plane to be visualized.
  42336. * @param {number} [size=1] - The side length of plane helper.
  42337. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  42338. */
  42339. constructor( plane, size = 1, hex = 0xffff00 ) {
  42340. const color = hex;
  42341. 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 ];
  42342. const geometry = new BufferGeometry();
  42343. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42344. geometry.computeBoundingSphere();
  42345. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42346. this.type = 'PlaneHelper';
  42347. /**
  42348. * The plane being visualized.
  42349. *
  42350. * @type {Plane}
  42351. */
  42352. this.plane = plane;
  42353. /**
  42354. * The side length of plane helper.
  42355. *
  42356. * @type {number}
  42357. * @default 1
  42358. */
  42359. this.size = size;
  42360. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  42361. const geometry2 = new BufferGeometry();
  42362. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42363. geometry2.computeBoundingSphere();
  42364. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42365. }
  42366. updateMatrixWorld( force ) {
  42367. this.position.set( 0, 0, 0 );
  42368. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42369. this.lookAt( this.plane.normal );
  42370. this.translateZ( - this.plane.constant );
  42371. super.updateMatrixWorld( force );
  42372. }
  42373. /**
  42374. * Updates the helper to match the position and direction of the
  42375. * light being visualized.
  42376. */
  42377. dispose() {
  42378. this.geometry.dispose();
  42379. this.material.dispose();
  42380. this.children[ 0 ].geometry.dispose();
  42381. this.children[ 0 ].material.dispose();
  42382. }
  42383. }
  42384. const _axis = /*@__PURE__*/ new Vector3();
  42385. let _lineGeometry, _coneGeometry;
  42386. /**
  42387. * An 3D arrow object for visualizing directions.
  42388. *
  42389. * ```js
  42390. * const dir = new THREE.Vector3( 1, 2, 0 );
  42391. *
  42392. * //normalize the direction vector (convert to vector of length 1)
  42393. * dir.normalize();
  42394. *
  42395. * const origin = new THREE.Vector3( 0, 0, 0 );
  42396. * const length = 1;
  42397. * const hex = 0xffff00;
  42398. *
  42399. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42400. * scene.add( arrowHelper );
  42401. * ```
  42402. *
  42403. * @augments Object3D
  42404. */
  42405. class ArrowHelper extends Object3D {
  42406. /**
  42407. * Constructs a new arrow helper.
  42408. *
  42409. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42410. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42411. * @param {number} [length=1] - Length of the arrow in world units.
  42412. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42413. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42414. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42415. */
  42416. 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 ) {
  42417. super();
  42418. this.type = 'ArrowHelper';
  42419. if ( _lineGeometry === undefined ) {
  42420. _lineGeometry = new BufferGeometry();
  42421. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42422. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42423. _coneGeometry.translate( 0, -0.5, 0 );
  42424. }
  42425. this.position.copy( origin );
  42426. /**
  42427. * The line part of the arrow helper.
  42428. *
  42429. * @type {Line}
  42430. */
  42431. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42432. this.line.matrixAutoUpdate = false;
  42433. this.add( this.line );
  42434. /**
  42435. * The cone part of the arrow helper.
  42436. *
  42437. * @type {Mesh}
  42438. */
  42439. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42440. this.cone.matrixAutoUpdate = false;
  42441. this.add( this.cone );
  42442. this.setDirection( dir );
  42443. this.setLength( length, headLength, headWidth );
  42444. }
  42445. /**
  42446. * Sets the direction of the helper.
  42447. *
  42448. * @param {Vector3} dir - The normalized direction vector.
  42449. */
  42450. setDirection( dir ) {
  42451. // dir is assumed to be normalized
  42452. if ( dir.y > 0.99999 ) {
  42453. this.quaternion.set( 0, 0, 0, 1 );
  42454. } else if ( dir.y < -0.99999 ) {
  42455. this.quaternion.set( 1, 0, 0, 0 );
  42456. } else {
  42457. _axis.set( dir.z, 0, - dir.x ).normalize();
  42458. const radians = Math.acos( dir.y );
  42459. this.quaternion.setFromAxisAngle( _axis, radians );
  42460. }
  42461. }
  42462. /**
  42463. * Sets the length of the helper.
  42464. *
  42465. * @param {number} length - Length of the arrow in world units.
  42466. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42467. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42468. */
  42469. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42470. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42471. this.line.updateMatrix();
  42472. this.cone.scale.set( headWidth, headLength, headWidth );
  42473. this.cone.position.y = length;
  42474. this.cone.updateMatrix();
  42475. }
  42476. /**
  42477. * Sets the color of the helper.
  42478. *
  42479. * @param {number|Color|string} color - The color to set.
  42480. */
  42481. setColor( color ) {
  42482. this.line.material.color.set( color );
  42483. this.cone.material.color.set( color );
  42484. }
  42485. copy( source ) {
  42486. super.copy( source, false );
  42487. this.line.copy( source.line );
  42488. this.cone.copy( source.cone );
  42489. return this;
  42490. }
  42491. /**
  42492. * Frees the GPU-related resources allocated by this instance. Call this
  42493. * method whenever this instance is no longer used in your app.
  42494. */
  42495. dispose() {
  42496. this.line.geometry.dispose();
  42497. this.line.material.dispose();
  42498. this.cone.geometry.dispose();
  42499. this.cone.material.dispose();
  42500. }
  42501. }
  42502. /**
  42503. * An axis object to visualize the 3 axes in a simple way.
  42504. * The X axis is red. The Y axis is green. The Z axis is blue.
  42505. *
  42506. * ```js
  42507. * const axesHelper = new THREE.AxesHelper( 5 );
  42508. * scene.add( axesHelper );
  42509. * ```
  42510. *
  42511. * @augments LineSegments
  42512. */
  42513. class AxesHelper extends LineSegments {
  42514. /**
  42515. * Constructs a new axes helper.
  42516. *
  42517. * @param {number} [size=1] - Size of the lines representing the axes.
  42518. */
  42519. constructor( size = 1 ) {
  42520. const vertices = [
  42521. 0, 0, 0, size, 0, 0,
  42522. 0, 0, 0, 0, size, 0,
  42523. 0, 0, 0, 0, 0, size
  42524. ];
  42525. const colors = [
  42526. 1, 0, 0, 1, 0.6, 0,
  42527. 0, 1, 0, 0.6, 1, 0,
  42528. 0, 0, 1, 0, 0.6, 1
  42529. ];
  42530. const geometry = new BufferGeometry();
  42531. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42532. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42533. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42534. super( geometry, material );
  42535. this.type = 'AxesHelper';
  42536. }
  42537. /**
  42538. * Defines the colors of the axes helper.
  42539. *
  42540. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42541. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42542. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42543. * @return {AxesHelper} A reference to this axes helper.
  42544. */
  42545. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42546. const color = new Color();
  42547. const array = this.geometry.attributes.color.array;
  42548. color.set( xAxisColor );
  42549. color.toArray( array, 0 );
  42550. color.toArray( array, 3 );
  42551. color.set( yAxisColor );
  42552. color.toArray( array, 6 );
  42553. color.toArray( array, 9 );
  42554. color.set( zAxisColor );
  42555. color.toArray( array, 12 );
  42556. color.toArray( array, 15 );
  42557. this.geometry.attributes.color.needsUpdate = true;
  42558. return this;
  42559. }
  42560. /**
  42561. * Frees the GPU-related resources allocated by this instance. Call this
  42562. * method whenever this instance is no longer used in your app.
  42563. */
  42564. dispose() {
  42565. this.geometry.dispose();
  42566. this.material.dispose();
  42567. }
  42568. }
  42569. /**
  42570. * This class is used to convert a series of paths to an array of
  42571. * shapes. It is specifically used in context of fonts and SVG.
  42572. */
  42573. class ShapePath {
  42574. /**
  42575. * Constructs a new shape path.
  42576. */
  42577. constructor() {
  42578. this.type = 'ShapePath';
  42579. /**
  42580. * The color of the shape.
  42581. *
  42582. * @type {Color}
  42583. */
  42584. this.color = new Color();
  42585. /**
  42586. * The paths that have been generated for this shape.
  42587. *
  42588. * @type {Array<Path>}
  42589. * @default null
  42590. */
  42591. this.subPaths = [];
  42592. /**
  42593. * The current path that is being generated.
  42594. *
  42595. * @type {?Path}
  42596. * @default null
  42597. */
  42598. this.currentPath = null;
  42599. }
  42600. /**
  42601. * Creates a new path and moves it current point to the given one.
  42602. *
  42603. * @param {number} x - The x coordinate.
  42604. * @param {number} y - The y coordinate.
  42605. * @return {ShapePath} A reference to this shape path.
  42606. */
  42607. moveTo( x, y ) {
  42608. this.currentPath = new Path();
  42609. this.subPaths.push( this.currentPath );
  42610. this.currentPath.moveTo( x, y );
  42611. return this;
  42612. }
  42613. /**
  42614. * Adds an instance of {@link LineCurve} to the path by connecting
  42615. * the current point with the given one.
  42616. *
  42617. * @param {number} x - The x coordinate of the end point.
  42618. * @param {number} y - The y coordinate of the end point.
  42619. * @return {ShapePath} A reference to this shape path.
  42620. */
  42621. lineTo( x, y ) {
  42622. this.currentPath.lineTo( x, y );
  42623. return this;
  42624. }
  42625. /**
  42626. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42627. * the current point with the given one.
  42628. *
  42629. * @param {number} aCPx - The x coordinate of the control point.
  42630. * @param {number} aCPy - The y coordinate of the control point.
  42631. * @param {number} aX - The x coordinate of the end point.
  42632. * @param {number} aY - The y coordinate of the end point.
  42633. * @return {ShapePath} A reference to this shape path.
  42634. */
  42635. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42636. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42637. return this;
  42638. }
  42639. /**
  42640. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42641. * the current point with the given one.
  42642. *
  42643. * @param {number} aCP1x - The x coordinate of the first control point.
  42644. * @param {number} aCP1y - The y coordinate of the first control point.
  42645. * @param {number} aCP2x - The x coordinate of the second control point.
  42646. * @param {number} aCP2y - The y coordinate of the second control point.
  42647. * @param {number} aX - The x coordinate of the end point.
  42648. * @param {number} aY - The y coordinate of the end point.
  42649. * @return {ShapePath} A reference to this shape path.
  42650. */
  42651. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42652. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42653. return this;
  42654. }
  42655. /**
  42656. * Adds an instance of {@link SplineCurve} to the path by connecting
  42657. * the current point with the given list of points.
  42658. *
  42659. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42660. * @return {ShapePath} A reference to this shape path.
  42661. */
  42662. splineThru( pts ) {
  42663. this.currentPath.splineThru( pts );
  42664. return this;
  42665. }
  42666. /**
  42667. * Converts the paths into an array of shapes.
  42668. *
  42669. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42670. * If this flag is set to `true`, then those are flipped.
  42671. * @return {Array<Shape>} An array of shapes.
  42672. */
  42673. toShapes( isCCW ) {
  42674. function toShapesNoHoles( inSubpaths ) {
  42675. const shapes = [];
  42676. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42677. const tmpPath = inSubpaths[ i ];
  42678. const tmpShape = new Shape();
  42679. tmpShape.curves = tmpPath.curves;
  42680. shapes.push( tmpShape );
  42681. }
  42682. return shapes;
  42683. }
  42684. function isPointInsidePolygon( inPt, inPolygon ) {
  42685. const polyLen = inPolygon.length;
  42686. // inPt on polygon contour => immediate success or
  42687. // toggling of inside/outside at every single! intersection point of an edge
  42688. // with the horizontal line through inPt, left of inPt
  42689. // not counting lowerY endpoints of edges and whole edges on that line
  42690. let inside = false;
  42691. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42692. let edgeLowPt = inPolygon[ p ];
  42693. let edgeHighPt = inPolygon[ q ];
  42694. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42695. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42696. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42697. // not parallel
  42698. if ( edgeDy < 0 ) {
  42699. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42700. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42701. }
  42702. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42703. if ( inPt.y === edgeLowPt.y ) {
  42704. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42705. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42706. } else {
  42707. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42708. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42709. if ( perpEdge < 0 ) continue;
  42710. inside = ! inside; // true intersection left of inPt
  42711. }
  42712. } else {
  42713. // parallel or collinear
  42714. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42715. // edge lies on the same horizontal line as inPt
  42716. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42717. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42718. // continue;
  42719. }
  42720. }
  42721. return inside;
  42722. }
  42723. const isClockWise = ShapeUtils.isClockWise;
  42724. const subPaths = this.subPaths;
  42725. if ( subPaths.length === 0 ) return [];
  42726. let solid, tmpPath, tmpShape;
  42727. const shapes = [];
  42728. if ( subPaths.length === 1 ) {
  42729. tmpPath = subPaths[ 0 ];
  42730. tmpShape = new Shape();
  42731. tmpShape.curves = tmpPath.curves;
  42732. shapes.push( tmpShape );
  42733. return shapes;
  42734. }
  42735. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42736. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42737. // log("Holes first", holesFirst);
  42738. const betterShapeHoles = [];
  42739. const newShapes = [];
  42740. let newShapeHoles = [];
  42741. let mainIdx = 0;
  42742. let tmpPoints;
  42743. newShapes[ mainIdx ] = undefined;
  42744. newShapeHoles[ mainIdx ] = [];
  42745. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42746. tmpPath = subPaths[ i ];
  42747. tmpPoints = tmpPath.getPoints();
  42748. solid = isClockWise( tmpPoints );
  42749. solid = isCCW ? ! solid : solid;
  42750. if ( solid ) {
  42751. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42752. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42753. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42754. if ( holesFirst ) mainIdx ++;
  42755. newShapeHoles[ mainIdx ] = [];
  42756. //log('cw', i);
  42757. } else {
  42758. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42759. //log('ccw', i);
  42760. }
  42761. }
  42762. // only Holes? -> probably all Shapes with wrong orientation
  42763. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42764. if ( newShapes.length > 1 ) {
  42765. let ambiguous = false;
  42766. let toChange = 0;
  42767. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42768. betterShapeHoles[ sIdx ] = [];
  42769. }
  42770. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42771. const sho = newShapeHoles[ sIdx ];
  42772. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42773. const ho = sho[ hIdx ];
  42774. let hole_unassigned = true;
  42775. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42776. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42777. if ( sIdx !== s2Idx ) toChange ++;
  42778. if ( hole_unassigned ) {
  42779. hole_unassigned = false;
  42780. betterShapeHoles[ s2Idx ].push( ho );
  42781. } else {
  42782. ambiguous = true;
  42783. }
  42784. }
  42785. }
  42786. if ( hole_unassigned ) {
  42787. betterShapeHoles[ sIdx ].push( ho );
  42788. }
  42789. }
  42790. }
  42791. if ( toChange > 0 && ambiguous === false ) {
  42792. newShapeHoles = betterShapeHoles;
  42793. }
  42794. }
  42795. let tmpHoles;
  42796. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42797. tmpShape = newShapes[ i ].s;
  42798. shapes.push( tmpShape );
  42799. tmpHoles = newShapeHoles[ i ];
  42800. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42801. tmpShape.holes.push( tmpHoles[ j ].h );
  42802. }
  42803. }
  42804. //log("shape", shapes);
  42805. return shapes;
  42806. }
  42807. }
  42808. /**
  42809. * Abstract base class for controls.
  42810. *
  42811. * @abstract
  42812. * @augments EventDispatcher
  42813. */
  42814. class Controls extends EventDispatcher {
  42815. /**
  42816. * Constructs a new controls instance.
  42817. *
  42818. * @param {Object3D} object - The object that is managed by the controls.
  42819. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42820. */
  42821. constructor( object, domElement = null ) {
  42822. super();
  42823. /**
  42824. * The object that is managed by the controls.
  42825. *
  42826. * @type {Object3D}
  42827. */
  42828. this.object = object;
  42829. /**
  42830. * The HTML element used for event listeners.
  42831. *
  42832. * @type {?HTMLElement}
  42833. * @default null
  42834. */
  42835. this.domElement = domElement;
  42836. /**
  42837. * Whether the controls responds to user input or not.
  42838. *
  42839. * @type {boolean}
  42840. * @default true
  42841. */
  42842. this.enabled = true;
  42843. /**
  42844. * The internal state of the controls.
  42845. *
  42846. * @type {number}
  42847. * @default -1
  42848. */
  42849. this.state = -1;
  42850. /**
  42851. * This object defines the keyboard input of the controls.
  42852. *
  42853. * @type {Object}
  42854. */
  42855. this.keys = {};
  42856. /**
  42857. * This object defines what type of actions are assigned to the available mouse buttons.
  42858. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42859. *
  42860. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42861. */
  42862. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42863. /**
  42864. * This object defines what type of actions are assigned to what kind of touch interaction.
  42865. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42866. *
  42867. * @type {{ONE: ?number, TWO: ?number}}
  42868. */
  42869. this.touches = { ONE: null, TWO: null };
  42870. }
  42871. /**
  42872. * Connects the controls to the DOM. This method has so called "side effects" since
  42873. * it adds the module's event listeners to the DOM.
  42874. *
  42875. * @param {HTMLElement} element - The DOM element to connect to.
  42876. */
  42877. connect( element ) {
  42878. if ( element === undefined ) {
  42879. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42880. return;
  42881. }
  42882. if ( this.domElement !== null ) this.disconnect();
  42883. this.domElement = element;
  42884. }
  42885. /**
  42886. * Disconnects the controls from the DOM.
  42887. */
  42888. disconnect() {}
  42889. /**
  42890. * Call this method if you no longer want use to the controls. It frees all internal
  42891. * resources and removes all event listeners.
  42892. */
  42893. dispose() {}
  42894. /**
  42895. * Controls should implement this method if they have to update their internal state
  42896. * per simulation step.
  42897. *
  42898. * @param {number} [delta] - The time delta in seconds.
  42899. */
  42900. update( /* delta */ ) {}
  42901. }
  42902. /**
  42903. * Scales the texture as large as possible within its surface without cropping
  42904. * or stretching the texture. The method preserves the original aspect ratio of
  42905. * the texture. Akin to CSS `object-fit: contain`
  42906. *
  42907. * @param {Texture} texture - The texture.
  42908. * @param {number} aspect - The texture's aspect ratio.
  42909. * @return {Texture} The updated texture.
  42910. */
  42911. function contain( texture, aspect ) {
  42912. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42913. if ( imageAspect > aspect ) {
  42914. texture.repeat.x = 1;
  42915. texture.repeat.y = imageAspect / aspect;
  42916. texture.offset.x = 0;
  42917. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42918. } else {
  42919. texture.repeat.x = aspect / imageAspect;
  42920. texture.repeat.y = 1;
  42921. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42922. texture.offset.y = 0;
  42923. }
  42924. return texture;
  42925. }
  42926. /**
  42927. * Scales the texture to the smallest possible size to fill the surface, leaving
  42928. * no empty space. The method preserves the original aspect ratio of the texture.
  42929. * Akin to CSS `object-fit: cover`.
  42930. *
  42931. * @param {Texture} texture - The texture.
  42932. * @param {number} aspect - The texture's aspect ratio.
  42933. * @return {Texture} The updated texture.
  42934. */
  42935. function cover( texture, aspect ) {
  42936. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42937. if ( imageAspect > aspect ) {
  42938. texture.repeat.x = aspect / imageAspect;
  42939. texture.repeat.y = 1;
  42940. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42941. texture.offset.y = 0;
  42942. } else {
  42943. texture.repeat.x = 1;
  42944. texture.repeat.y = imageAspect / aspect;
  42945. texture.offset.x = 0;
  42946. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42947. }
  42948. return texture;
  42949. }
  42950. /**
  42951. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42952. *
  42953. * @param {Texture} texture - The texture.
  42954. * @return {Texture} The updated texture.
  42955. */
  42956. function fill( texture ) {
  42957. texture.repeat.x = 1;
  42958. texture.repeat.y = 1;
  42959. texture.offset.x = 0;
  42960. texture.offset.y = 0;
  42961. return texture;
  42962. }
  42963. /**
  42964. * Determines how many bytes must be used to represent the texture.
  42965. *
  42966. * @param {number} width - The width of the texture.
  42967. * @param {number} height - The height of the texture.
  42968. * @param {number} format - The texture's format.
  42969. * @param {number} type - The texture's type.
  42970. * @return {number} The byte length.
  42971. */
  42972. function getByteLength( width, height, format, type ) {
  42973. const typeByteLength = getTextureTypeByteLength( type );
  42974. switch ( format ) {
  42975. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42976. case AlphaFormat:
  42977. return width * height;
  42978. case RedFormat:
  42979. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42980. case RedIntegerFormat:
  42981. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42982. case RGFormat:
  42983. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42984. case RGIntegerFormat:
  42985. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42986. case RGBFormat:
  42987. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42988. case RGBAFormat:
  42989. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42990. case RGBAIntegerFormat:
  42991. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42992. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42993. case RGB_S3TC_DXT1_Format:
  42994. case RGBA_S3TC_DXT1_Format:
  42995. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42996. case RGBA_S3TC_DXT3_Format:
  42997. case RGBA_S3TC_DXT5_Format:
  42998. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42999. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  43000. case RGB_PVRTC_2BPPV1_Format:
  43001. case RGBA_PVRTC_2BPPV1_Format:
  43002. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  43003. case RGB_PVRTC_4BPPV1_Format:
  43004. case RGBA_PVRTC_4BPPV1_Format:
  43005. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  43006. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  43007. case RGB_ETC1_Format:
  43008. case RGB_ETC2_Format:
  43009. case R11_EAC_Format:
  43010. case SIGNED_R11_EAC_Format:
  43011. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  43012. case RGBA_ETC2_EAC_Format:
  43013. case RG11_EAC_Format:
  43014. case SIGNED_RG11_EAC_Format:
  43015. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43016. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  43017. case RGBA_ASTC_4x4_Format:
  43018. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43019. case RGBA_ASTC_5x4_Format:
  43020. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43021. case RGBA_ASTC_5x5_Format:
  43022. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43023. case RGBA_ASTC_6x5_Format:
  43024. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43025. case RGBA_ASTC_6x6_Format:
  43026. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43027. case RGBA_ASTC_8x5_Format:
  43028. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43029. case RGBA_ASTC_8x6_Format:
  43030. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43031. case RGBA_ASTC_8x8_Format:
  43032. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43033. case RGBA_ASTC_10x5_Format:
  43034. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43035. case RGBA_ASTC_10x6_Format:
  43036. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43037. case RGBA_ASTC_10x8_Format:
  43038. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43039. case RGBA_ASTC_10x10_Format:
  43040. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43041. case RGBA_ASTC_12x10_Format:
  43042. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43043. case RGBA_ASTC_12x12_Format:
  43044. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  43045. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  43046. case RGBA_BPTC_Format:
  43047. case RGB_BPTC_SIGNED_Format:
  43048. case RGB_BPTC_UNSIGNED_Format:
  43049. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43050. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  43051. case RED_RGTC1_Format:
  43052. case SIGNED_RED_RGTC1_Format:
  43053. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  43054. case RED_GREEN_RGTC2_Format:
  43055. case SIGNED_RED_GREEN_RGTC2_Format:
  43056. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43057. }
  43058. throw new Error(
  43059. `Unable to determine texture byte length for ${format} format.`,
  43060. );
  43061. }
  43062. function getTextureTypeByteLength( type ) {
  43063. switch ( type ) {
  43064. case UnsignedByteType:
  43065. case ByteType:
  43066. return { byteLength: 1, components: 1 };
  43067. case UnsignedShortType:
  43068. case ShortType:
  43069. case HalfFloatType:
  43070. return { byteLength: 2, components: 1 };
  43071. case UnsignedShort4444Type:
  43072. case UnsignedShort5551Type:
  43073. return { byteLength: 2, components: 4 };
  43074. case UnsignedIntType:
  43075. case IntType:
  43076. case FloatType:
  43077. return { byteLength: 4, components: 1 };
  43078. case UnsignedInt5999Type:
  43079. case UnsignedInt101111Type:
  43080. return { byteLength: 4, components: 3 };
  43081. }
  43082. throw new Error( `Unknown texture type ${type}.` );
  43083. }
  43084. /**
  43085. * A class containing utility functions for textures.
  43086. *
  43087. * @hideconstructor
  43088. */
  43089. class TextureUtils {
  43090. /**
  43091. * Scales the texture as large as possible within its surface without cropping
  43092. * or stretching the texture. The method preserves the original aspect ratio of
  43093. * the texture. Akin to CSS `object-fit: contain`
  43094. *
  43095. * @param {Texture} texture - The texture.
  43096. * @param {number} aspect - The texture's aspect ratio.
  43097. * @return {Texture} The updated texture.
  43098. */
  43099. static contain( texture, aspect ) {
  43100. return contain( texture, aspect );
  43101. }
  43102. /**
  43103. * Scales the texture to the smallest possible size to fill the surface, leaving
  43104. * no empty space. The method preserves the original aspect ratio of the texture.
  43105. * Akin to CSS `object-fit: cover`.
  43106. *
  43107. * @param {Texture} texture - The texture.
  43108. * @param {number} aspect - The texture's aspect ratio.
  43109. * @return {Texture} The updated texture.
  43110. */
  43111. static cover( texture, aspect ) {
  43112. return cover( texture, aspect );
  43113. }
  43114. /**
  43115. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43116. *
  43117. * @param {Texture} texture - The texture.
  43118. * @return {Texture} The updated texture.
  43119. */
  43120. static fill( texture ) {
  43121. return fill( texture );
  43122. }
  43123. /**
  43124. * Determines how many bytes must be used to represent the texture.
  43125. *
  43126. * @param {number} width - The width of the texture.
  43127. * @param {number} height - The height of the texture.
  43128. * @param {number} format - The texture's format.
  43129. * @param {number} type - The texture's type.
  43130. * @return {number} The byte length.
  43131. */
  43132. static getByteLength( width, height, format, type ) {
  43133. return getByteLength( width, height, format, type );
  43134. }
  43135. }
  43136. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43137. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43138. revision: REVISION,
  43139. } } ) );
  43140. }
  43141. if ( typeof window !== 'undefined' ) {
  43142. if ( window.__THREE__ ) {
  43143. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43144. } else {
  43145. window.__THREE__ = REVISION;
  43146. }
  43147. }
  43148. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, BezierInterpolant, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, Compatibility, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeDepthTexture, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExternalTexture, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, FrustumArray, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateBezier, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, MaterialBlending, MaterialLoader, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoNormalPacking, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NormalGAPacking, NormalRGPacking, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, R11_EAC_Format, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RG11_EAC_Format, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RenderTarget3D, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, SIGNED_R11_EAC_Format, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SIGNED_RG11_EAC_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, arrayNeedsUint32, cloneUniforms, createCanvasElement, createElementNS, error, getByteLength, getConsoleFunction, getUnlitUniformColorSpace, isTypedArray, log, mergeUniforms, probeAsync, setConsoleFunction, warn, warnOnce };
粤ICP备19079148号