three.core.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '180dev';
  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. * A `source + destination` blending equation.
  145. *
  146. * @type {number}
  147. * @constant
  148. */
  149. const AddEquation = 100;
  150. /**
  151. * A `source - destination` blending equation.
  152. *
  153. * @type {number}
  154. * @constant
  155. */
  156. const SubtractEquation = 101;
  157. /**
  158. * A `destination - source` blending equation.
  159. *
  160. * @type {number}
  161. * @constant
  162. */
  163. const ReverseSubtractEquation = 102;
  164. /**
  165. * A blend equation that uses the minimum of source and destination.
  166. *
  167. * @type {number}
  168. * @constant
  169. */
  170. const MinEquation = 103;
  171. /**
  172. * A blend equation that uses the maximum of source and destination.
  173. *
  174. * @type {number}
  175. * @constant
  176. */
  177. const MaxEquation = 104;
  178. /**
  179. * Multiplies all colors by `0`.
  180. *
  181. * @type {number}
  182. * @constant
  183. */
  184. const ZeroFactor = 200;
  185. /**
  186. * Multiplies all colors by `1`.
  187. *
  188. * @type {number}
  189. * @constant
  190. */
  191. const OneFactor = 201;
  192. /**
  193. * Multiplies all colors by the source colors.
  194. *
  195. * @type {number}
  196. * @constant
  197. */
  198. const SrcColorFactor = 202;
  199. /**
  200. * Multiplies all colors by `1` minus each source color.
  201. *
  202. * @type {number}
  203. * @constant
  204. */
  205. const OneMinusSrcColorFactor = 203;
  206. /**
  207. * Multiplies all colors by the source alpha value.
  208. *
  209. * @type {number}
  210. * @constant
  211. */
  212. const SrcAlphaFactor = 204;
  213. /**
  214. * Multiplies all colors by 1 minus the source alpha value.
  215. *
  216. * @type {number}
  217. * @constant
  218. */
  219. const OneMinusSrcAlphaFactor = 205;
  220. /**
  221. * Multiplies all colors by the destination alpha value.
  222. *
  223. * @type {number}
  224. * @constant
  225. */
  226. const DstAlphaFactor = 206;
  227. /**
  228. * Multiplies all colors by `1` minus the destination alpha value.
  229. *
  230. * @type {number}
  231. * @constant
  232. */
  233. const OneMinusDstAlphaFactor = 207;
  234. /**
  235. * Multiplies all colors by the destination color.
  236. *
  237. * @type {number}
  238. * @constant
  239. */
  240. const DstColorFactor = 208;
  241. /**
  242. * Multiplies all colors by `1` minus each destination color.
  243. *
  244. * @type {number}
  245. * @constant
  246. */
  247. const OneMinusDstColorFactor = 209;
  248. /**
  249. * Multiplies the RGB colors by the smaller of either the source alpha
  250. * value or the value of `1` minus the destination alpha value. The alpha
  251. * value is multiplied by `1`.
  252. *
  253. * @type {number}
  254. * @constant
  255. */
  256. const SrcAlphaSaturateFactor = 210;
  257. /**
  258. * Multiplies all colors by a constant color.
  259. *
  260. * @type {number}
  261. * @constant
  262. */
  263. const ConstantColorFactor = 211;
  264. /**
  265. * Multiplies all colors by `1` minus a constant color.
  266. *
  267. * @type {number}
  268. * @constant
  269. */
  270. const OneMinusConstantColorFactor = 212;
  271. /**
  272. * Multiplies all colors by a constant alpha value.
  273. *
  274. * @type {number}
  275. * @constant
  276. */
  277. const ConstantAlphaFactor = 213;
  278. /**
  279. * Multiplies all colors by 1 minus a constant alpha value.
  280. *
  281. * @type {number}
  282. * @constant
  283. */
  284. const OneMinusConstantAlphaFactor = 214;
  285. /**
  286. * Never pass.
  287. *
  288. * @type {number}
  289. * @constant
  290. */
  291. const NeverDepth = 0;
  292. /**
  293. * Always pass.
  294. *
  295. * @type {number}
  296. * @constant
  297. */
  298. const AlwaysDepth = 1;
  299. /**
  300. * Pass if the incoming value is less than the depth buffer value.
  301. *
  302. * @type {number}
  303. * @constant
  304. */
  305. const LessDepth = 2;
  306. /**
  307. * Pass if the incoming value is less than or equal to the depth buffer value.
  308. *
  309. * @type {number}
  310. * @constant
  311. */
  312. const LessEqualDepth = 3;
  313. /**
  314. * Pass if the incoming value equals the depth buffer value.
  315. *
  316. * @type {number}
  317. * @constant
  318. */
  319. const EqualDepth = 4;
  320. /**
  321. * Pass if the incoming value is greater than or equal to the depth buffer value.
  322. *
  323. * @type {number}
  324. * @constant
  325. */
  326. const GreaterEqualDepth = 5;
  327. /**
  328. * Pass if the incoming value is greater than the depth buffer value.
  329. *
  330. * @type {number}
  331. * @constant
  332. */
  333. const GreaterDepth = 6;
  334. /**
  335. * Pass if the incoming value is not equal to the depth buffer value.
  336. *
  337. * @type {number}
  338. * @constant
  339. */
  340. const NotEqualDepth = 7;
  341. /**
  342. * Multiplies the environment map color with the surface color.
  343. *
  344. * @type {number}
  345. * @constant
  346. */
  347. const MultiplyOperation = 0;
  348. /**
  349. * Uses reflectivity to blend between the two colors.
  350. *
  351. * @type {number}
  352. * @constant
  353. */
  354. const MixOperation = 1;
  355. /**
  356. * Adds the two colors.
  357. *
  358. * @type {number}
  359. * @constant
  360. */
  361. const AddOperation = 2;
  362. /**
  363. * No tone mapping is applied.
  364. *
  365. * @type {number}
  366. * @constant
  367. */
  368. const NoToneMapping = 0;
  369. /**
  370. * Linear tone mapping.
  371. *
  372. * @type {number}
  373. * @constant
  374. */
  375. const LinearToneMapping = 1;
  376. /**
  377. * Reinhard tone mapping.
  378. *
  379. * @type {number}
  380. * @constant
  381. */
  382. const ReinhardToneMapping = 2;
  383. /**
  384. * Cineon tone mapping.
  385. *
  386. * @type {number}
  387. * @constant
  388. */
  389. const CineonToneMapping = 3;
  390. /**
  391. * ACES Filmic tone mapping.
  392. *
  393. * @type {number}
  394. * @constant
  395. */
  396. const ACESFilmicToneMapping = 4;
  397. /**
  398. * Custom tone mapping.
  399. *
  400. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  401. *
  402. * @type {number}
  403. * @constant
  404. */
  405. const CustomToneMapping = 5;
  406. /**
  407. * AgX tone mapping.
  408. *
  409. * @type {number}
  410. * @constant
  411. */
  412. const AgXToneMapping = 6;
  413. /**
  414. * Neutral tone mapping.
  415. *
  416. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  417. *
  418. * @type {number}
  419. * @constant
  420. */
  421. const NeutralToneMapping = 7;
  422. /**
  423. * The skinned mesh shares the same world space as the skeleton.
  424. *
  425. * @type {string}
  426. * @constant
  427. */
  428. const AttachedBindMode = 'attached';
  429. /**
  430. * The skinned mesh does not share the same world space as the skeleton.
  431. * This is useful when a skeleton is shared across multiple skinned meshes.
  432. *
  433. * @type {string}
  434. * @constant
  435. */
  436. const DetachedBindMode = 'detached';
  437. /**
  438. * Maps textures using the geometry's UV coordinates.
  439. *
  440. * @type {number}
  441. * @constant
  442. */
  443. const UVMapping = 300;
  444. /**
  445. * Reflection mapping for cube textures.
  446. *
  447. * @type {number}
  448. * @constant
  449. */
  450. const CubeReflectionMapping = 301;
  451. /**
  452. * Refraction mapping for cube textures.
  453. *
  454. * @type {number}
  455. * @constant
  456. */
  457. const CubeRefractionMapping = 302;
  458. /**
  459. * Reflection mapping for equirectangular textures.
  460. *
  461. * @type {number}
  462. * @constant
  463. */
  464. const EquirectangularReflectionMapping = 303;
  465. /**
  466. * Refraction mapping for equirectangular textures.
  467. *
  468. * @type {number}
  469. * @constant
  470. */
  471. const EquirectangularRefractionMapping = 304;
  472. /**
  473. * Reflection mapping for PMREM textures.
  474. *
  475. * @type {number}
  476. * @constant
  477. */
  478. const CubeUVReflectionMapping = 306;
  479. /**
  480. * The texture will simply repeat to infinity.
  481. *
  482. * @type {number}
  483. * @constant
  484. */
  485. const RepeatWrapping = 1000;
  486. /**
  487. * The last pixel of the texture stretches to the edge of the mesh.
  488. *
  489. * @type {number}
  490. * @constant
  491. */
  492. const ClampToEdgeWrapping = 1001;
  493. /**
  494. * The texture will repeats to infinity, mirroring on each repeat.
  495. *
  496. * @type {number}
  497. * @constant
  498. */
  499. const MirroredRepeatWrapping = 1002;
  500. /**
  501. * Returns the value of the texture element that is nearest (in Manhattan distance)
  502. * to the specified texture coordinates.
  503. *
  504. * @type {number}
  505. * @constant
  506. */
  507. const NearestFilter = 1003;
  508. /**
  509. * Chooses the mipmap that most closely matches the size of the pixel being textured
  510. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  511. * to produce a texture value.
  512. *
  513. * @type {number}
  514. * @constant
  515. */
  516. const NearestMipmapNearestFilter = 1004;
  517. const NearestMipMapNearestFilter = 1004; // legacy
  518. /**
  519. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  520. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  521. * The final texture value is a weighted average of those two values.
  522. *
  523. * @type {number}
  524. * @constant
  525. */
  526. const NearestMipmapLinearFilter = 1005;
  527. const NearestMipMapLinearFilter = 1005; // legacy
  528. /**
  529. * Returns the weighted average of the four texture elements that are closest to the specified
  530. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  531. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  532. *
  533. * @type {number}
  534. * @constant
  535. */
  536. const LinearFilter = 1006;
  537. /**
  538. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  539. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  540. * center of the pixel) to produce a texture value.
  541. *
  542. * @type {number}
  543. * @constant
  544. */
  545. const LinearMipmapNearestFilter = 1007;
  546. const LinearMipMapNearestFilter = 1007; // legacy
  547. /**
  548. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  549. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  550. * is a weighted average of those two values.
  551. *
  552. * @type {number}
  553. * @constant
  554. */
  555. const LinearMipmapLinearFilter = 1008;
  556. const LinearMipMapLinearFilter = 1008; // legacy
  557. /**
  558. * An unsigned byte data type for textures.
  559. *
  560. * @type {number}
  561. * @constant
  562. */
  563. const UnsignedByteType = 1009;
  564. /**
  565. * A byte data type for textures.
  566. *
  567. * @type {number}
  568. * @constant
  569. */
  570. const ByteType = 1010;
  571. /**
  572. * A short data type for textures.
  573. *
  574. * @type {number}
  575. * @constant
  576. */
  577. const ShortType = 1011;
  578. /**
  579. * An unsigned short data type for textures.
  580. *
  581. * @type {number}
  582. * @constant
  583. */
  584. const UnsignedShortType = 1012;
  585. /**
  586. * An int data type for textures.
  587. *
  588. * @type {number}
  589. * @constant
  590. */
  591. const IntType = 1013;
  592. /**
  593. * An unsigned int data type for textures.
  594. *
  595. * @type {number}
  596. * @constant
  597. */
  598. const UnsignedIntType = 1014;
  599. /**
  600. * A float data type for textures.
  601. *
  602. * @type {number}
  603. * @constant
  604. */
  605. const FloatType = 1015;
  606. /**
  607. * A half float data type for textures.
  608. *
  609. * @type {number}
  610. * @constant
  611. */
  612. const HalfFloatType = 1016;
  613. /**
  614. * An unsigned short 4_4_4_4 (packed) data type for textures.
  615. *
  616. * @type {number}
  617. * @constant
  618. */
  619. const UnsignedShort4444Type = 1017;
  620. /**
  621. * An unsigned short 5_5_5_1 (packed) data type for textures.
  622. *
  623. * @type {number}
  624. * @constant
  625. */
  626. const UnsignedShort5551Type = 1018;
  627. /**
  628. * An unsigned int 24_8 data type for textures.
  629. *
  630. * @type {number}
  631. * @constant
  632. */
  633. const UnsignedInt248Type = 1020;
  634. /**
  635. * An unsigned int 5_9_9_9 (packed) data type for textures.
  636. *
  637. * @type {number}
  638. * @constant
  639. */
  640. const UnsignedInt5999Type = 35902;
  641. /**
  642. * An unsigned int 10_11_11 (packed) data type for textures.
  643. *
  644. * @type {number}
  645. * @constant
  646. */
  647. const UnsignedInt101111Type = 35899;
  648. /**
  649. * Discards the red, green and blue components and reads just the alpha component.
  650. *
  651. * @type {number}
  652. * @constant
  653. */
  654. const AlphaFormat = 1021;
  655. /**
  656. * Discards the alpha component and reads the red, green and blue component.
  657. *
  658. * @type {number}
  659. * @constant
  660. */
  661. const RGBFormat = 1022;
  662. /**
  663. * Reads the red, green, blue and alpha components.
  664. *
  665. * @type {number}
  666. * @constant
  667. */
  668. const RGBAFormat = 1023;
  669. /**
  670. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  671. *
  672. * @type {number}
  673. * @constant
  674. */
  675. const DepthFormat = 1026;
  676. /**
  677. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  678. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  679. *
  680. * @type {number}
  681. * @constant
  682. */
  683. const DepthStencilFormat = 1027;
  684. /**
  685. * Discards the green, blue and alpha components and reads just the red component.
  686. *
  687. * @type {number}
  688. * @constant
  689. */
  690. const RedFormat = 1028;
  691. /**
  692. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  693. *
  694. * @type {number}
  695. * @constant
  696. */
  697. const RedIntegerFormat = 1029;
  698. /**
  699. * Discards the alpha, and blue components and reads the red, and green components.
  700. *
  701. * @type {number}
  702. * @constant
  703. */
  704. const RGFormat = 1030;
  705. /**
  706. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  707. *
  708. * @type {number}
  709. * @constant
  710. */
  711. const RGIntegerFormat = 1031;
  712. /**
  713. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  714. *
  715. * @type {number}
  716. * @constant
  717. */
  718. const RGBIntegerFormat = 1032;
  719. /**
  720. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  721. *
  722. * @type {number}
  723. * @constant
  724. */
  725. const RGBAIntegerFormat = 1033;
  726. /**
  727. * A DXT1-compressed image in an RGB image format.
  728. *
  729. * @type {number}
  730. * @constant
  731. */
  732. const RGB_S3TC_DXT1_Format = 33776;
  733. /**
  734. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  735. *
  736. * @type {number}
  737. * @constant
  738. */
  739. const RGBA_S3TC_DXT1_Format = 33777;
  740. /**
  741. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  742. *
  743. * @type {number}
  744. * @constant
  745. */
  746. const RGBA_S3TC_DXT3_Format = 33778;
  747. /**
  748. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  749. * compression in how the alpha compression is done.
  750. *
  751. * @type {number}
  752. * @constant
  753. */
  754. const RGBA_S3TC_DXT5_Format = 33779;
  755. /**
  756. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  757. *
  758. * @type {number}
  759. * @constant
  760. */
  761. const RGB_PVRTC_4BPPV1_Format = 35840;
  762. /**
  763. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  764. *
  765. * @type {number}
  766. * @constant
  767. */
  768. const RGB_PVRTC_2BPPV1_Format = 35841;
  769. /**
  770. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  771. *
  772. * @type {number}
  773. * @constant
  774. */
  775. const RGBA_PVRTC_4BPPV1_Format = 35842;
  776. /**
  777. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  778. *
  779. * @type {number}
  780. * @constant
  781. */
  782. const RGBA_PVRTC_2BPPV1_Format = 35843;
  783. /**
  784. * ETC1 RGB format.
  785. *
  786. * @type {number}
  787. * @constant
  788. */
  789. const RGB_ETC1_Format = 36196;
  790. /**
  791. * ETC2 RGB format.
  792. *
  793. * @type {number}
  794. * @constant
  795. */
  796. const RGB_ETC2_Format = 37492;
  797. /**
  798. * ETC2 RGBA format.
  799. *
  800. * @type {number}
  801. * @constant
  802. */
  803. const RGBA_ETC2_EAC_Format = 37496;
  804. /**
  805. * ASTC RGBA 4x4 format.
  806. *
  807. * @type {number}
  808. * @constant
  809. */
  810. const RGBA_ASTC_4x4_Format = 37808;
  811. /**
  812. * ASTC RGBA 5x4 format.
  813. *
  814. * @type {number}
  815. * @constant
  816. */
  817. const RGBA_ASTC_5x4_Format = 37809;
  818. /**
  819. * ASTC RGBA 5x5 format.
  820. *
  821. * @type {number}
  822. * @constant
  823. */
  824. const RGBA_ASTC_5x5_Format = 37810;
  825. /**
  826. * ASTC RGBA 6x5 format.
  827. *
  828. * @type {number}
  829. * @constant
  830. */
  831. const RGBA_ASTC_6x5_Format = 37811;
  832. /**
  833. * ASTC RGBA 6x6 format.
  834. *
  835. * @type {number}
  836. * @constant
  837. */
  838. const RGBA_ASTC_6x6_Format = 37812;
  839. /**
  840. * ASTC RGBA 8x5 format.
  841. *
  842. * @type {number}
  843. * @constant
  844. */
  845. const RGBA_ASTC_8x5_Format = 37813;
  846. /**
  847. * ASTC RGBA 8x6 format.
  848. *
  849. * @type {number}
  850. * @constant
  851. */
  852. const RGBA_ASTC_8x6_Format = 37814;
  853. /**
  854. * ASTC RGBA 8x8 format.
  855. *
  856. * @type {number}
  857. * @constant
  858. */
  859. const RGBA_ASTC_8x8_Format = 37815;
  860. /**
  861. * ASTC RGBA 10x5 format.
  862. *
  863. * @type {number}
  864. * @constant
  865. */
  866. const RGBA_ASTC_10x5_Format = 37816;
  867. /**
  868. * ASTC RGBA 10x6 format.
  869. *
  870. * @type {number}
  871. * @constant
  872. */
  873. const RGBA_ASTC_10x6_Format = 37817;
  874. /**
  875. * ASTC RGBA 10x8 format.
  876. *
  877. * @type {number}
  878. * @constant
  879. */
  880. const RGBA_ASTC_10x8_Format = 37818;
  881. /**
  882. * ASTC RGBA 10x10 format.
  883. *
  884. * @type {number}
  885. * @constant
  886. */
  887. const RGBA_ASTC_10x10_Format = 37819;
  888. /**
  889. * ASTC RGBA 12x10 format.
  890. *
  891. * @type {number}
  892. * @constant
  893. */
  894. const RGBA_ASTC_12x10_Format = 37820;
  895. /**
  896. * ASTC RGBA 12x12 format.
  897. *
  898. * @type {number}
  899. * @constant
  900. */
  901. const RGBA_ASTC_12x12_Format = 37821;
  902. /**
  903. * BPTC RGBA format.
  904. *
  905. * @type {number}
  906. * @constant
  907. */
  908. const RGBA_BPTC_Format = 36492;
  909. /**
  910. * BPTC Signed RGB format.
  911. *
  912. * @type {number}
  913. * @constant
  914. */
  915. const RGB_BPTC_SIGNED_Format = 36494;
  916. /**
  917. * BPTC Unsigned RGB format.
  918. *
  919. * @type {number}
  920. * @constant
  921. */
  922. const RGB_BPTC_UNSIGNED_Format = 36495;
  923. /**
  924. * RGTC1 Red format.
  925. *
  926. * @type {number}
  927. * @constant
  928. */
  929. const RED_RGTC1_Format = 36283;
  930. /**
  931. * RGTC1 Signed Red format.
  932. *
  933. * @type {number}
  934. * @constant
  935. */
  936. const SIGNED_RED_RGTC1_Format = 36284;
  937. /**
  938. * RGTC2 Red Green format.
  939. *
  940. * @type {number}
  941. * @constant
  942. */
  943. const RED_GREEN_RGTC2_Format = 36285;
  944. /**
  945. * RGTC2 Signed Red Green format.
  946. *
  947. * @type {number}
  948. * @constant
  949. */
  950. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  951. /**
  952. * Animations are played once.
  953. *
  954. * @type {number}
  955. * @constant
  956. */
  957. const LoopOnce = 2200;
  958. /**
  959. * Animations are played with a chosen number of repetitions, each time jumping from
  960. * the end of the clip directly to its beginning.
  961. *
  962. * @type {number}
  963. * @constant
  964. */
  965. const LoopRepeat = 2201;
  966. /**
  967. * Animations are played with a chosen number of repetitions, alternately playing forward
  968. * and backward.
  969. *
  970. * @type {number}
  971. * @constant
  972. */
  973. const LoopPingPong = 2202;
  974. /**
  975. * Discrete interpolation mode for keyframe tracks.
  976. *
  977. * @type {number}
  978. * @constant
  979. */
  980. const InterpolateDiscrete = 2300;
  981. /**
  982. * Linear interpolation mode for keyframe tracks.
  983. *
  984. * @type {number}
  985. * @constant
  986. */
  987. const InterpolateLinear = 2301;
  988. /**
  989. * Smooth interpolation mode for keyframe tracks.
  990. *
  991. * @type {number}
  992. * @constant
  993. */
  994. const InterpolateSmooth = 2302;
  995. /**
  996. * Zero curvature ending for animations.
  997. *
  998. * @type {number}
  999. * @constant
  1000. */
  1001. const ZeroCurvatureEnding = 2400;
  1002. /**
  1003. * Zero slope ending for animations.
  1004. *
  1005. * @type {number}
  1006. * @constant
  1007. */
  1008. const ZeroSlopeEnding = 2401;
  1009. /**
  1010. * Wrap around ending for animations.
  1011. *
  1012. * @type {number}
  1013. * @constant
  1014. */
  1015. const WrapAroundEnding = 2402;
  1016. /**
  1017. * Default animation blend mode.
  1018. *
  1019. * @type {number}
  1020. * @constant
  1021. */
  1022. const NormalAnimationBlendMode = 2500;
  1023. /**
  1024. * Additive animation blend mode. Can be used to layer motions on top of
  1025. * each other to build complex performances from smaller re-usable assets.
  1026. *
  1027. * @type {number}
  1028. * @constant
  1029. */
  1030. const AdditiveAnimationBlendMode = 2501;
  1031. /**
  1032. * For every three vertices draw a single triangle.
  1033. *
  1034. * @type {number}
  1035. * @constant
  1036. */
  1037. const TrianglesDrawMode = 0;
  1038. /**
  1039. * For each vertex draw a triangle from the last three vertices.
  1040. *
  1041. * @type {number}
  1042. * @constant
  1043. */
  1044. const TriangleStripDrawMode = 1;
  1045. /**
  1046. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1047. *
  1048. * @type {number}
  1049. * @constant
  1050. */
  1051. const TriangleFanDrawMode = 2;
  1052. /**
  1053. * Basic depth packing.
  1054. *
  1055. * @type {number}
  1056. * @constant
  1057. */
  1058. const BasicDepthPacking = 3200;
  1059. /**
  1060. * A depth value is packed into 32 bit RGBA.
  1061. *
  1062. * @type {number}
  1063. * @constant
  1064. */
  1065. const RGBADepthPacking = 3201;
  1066. /**
  1067. * A depth value is packed into 24 bit RGB.
  1068. *
  1069. * @type {number}
  1070. * @constant
  1071. */
  1072. const RGBDepthPacking = 3202;
  1073. /**
  1074. * A depth value is packed into 16 bit RG.
  1075. *
  1076. * @type {number}
  1077. * @constant
  1078. */
  1079. const RGDepthPacking = 3203;
  1080. /**
  1081. * Normal information is relative to the underlying surface.
  1082. *
  1083. * @type {number}
  1084. * @constant
  1085. */
  1086. const TangentSpaceNormalMap = 0;
  1087. /**
  1088. * Normal information is relative to the object orientation.
  1089. *
  1090. * @type {number}
  1091. * @constant
  1092. */
  1093. const ObjectSpaceNormalMap = 1;
  1094. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1095. /**
  1096. * No color space.
  1097. *
  1098. * @type {string}
  1099. * @constant
  1100. */
  1101. const NoColorSpace = '';
  1102. /**
  1103. * sRGB color space.
  1104. *
  1105. * @type {string}
  1106. * @constant
  1107. */
  1108. const SRGBColorSpace = 'srgb';
  1109. /**
  1110. * sRGB-linear color space.
  1111. *
  1112. * @type {string}
  1113. * @constant
  1114. */
  1115. const LinearSRGBColorSpace = 'srgb-linear';
  1116. /**
  1117. * Linear transfer function.
  1118. *
  1119. * @type {string}
  1120. * @constant
  1121. */
  1122. const LinearTransfer = 'linear';
  1123. /**
  1124. * sRGB transfer function.
  1125. *
  1126. * @type {string}
  1127. * @constant
  1128. */
  1129. const SRGBTransfer = 'srgb';
  1130. /**
  1131. * Sets the stencil buffer value to `0`.
  1132. *
  1133. * @type {number}
  1134. * @constant
  1135. */
  1136. const ZeroStencilOp = 0;
  1137. /**
  1138. * Keeps the current value.
  1139. *
  1140. * @type {number}
  1141. * @constant
  1142. */
  1143. const KeepStencilOp = 7680;
  1144. /**
  1145. * Sets the stencil buffer value to the specified reference value.
  1146. *
  1147. * @type {number}
  1148. * @constant
  1149. */
  1150. const ReplaceStencilOp = 7681;
  1151. /**
  1152. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1153. *
  1154. * @type {number}
  1155. * @constant
  1156. */
  1157. const IncrementStencilOp = 7682;
  1158. /**
  1159. * Decrements the current stencil buffer value. Clamps to `0`.
  1160. *
  1161. * @type {number}
  1162. * @constant
  1163. */
  1164. const DecrementStencilOp = 7683;
  1165. /**
  1166. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1167. * the maximum representable unsigned value.
  1168. *
  1169. * @type {number}
  1170. * @constant
  1171. */
  1172. const IncrementWrapStencilOp = 34055;
  1173. /**
  1174. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1175. * unsigned value when decrementing a stencil buffer value of `0`.
  1176. *
  1177. * @type {number}
  1178. * @constant
  1179. */
  1180. const DecrementWrapStencilOp = 34056;
  1181. /**
  1182. * Inverts the current stencil buffer value bitwise.
  1183. *
  1184. * @type {number}
  1185. * @constant
  1186. */
  1187. const InvertStencilOp = 5386;
  1188. /**
  1189. * Will never return true.
  1190. *
  1191. * @type {number}
  1192. * @constant
  1193. */
  1194. const NeverStencilFunc = 512;
  1195. /**
  1196. * Will return true if the stencil reference value is less than the current stencil value.
  1197. *
  1198. * @type {number}
  1199. * @constant
  1200. */
  1201. const LessStencilFunc = 513;
  1202. /**
  1203. * Will return true if the stencil reference value is equal to the current stencil value.
  1204. *
  1205. * @type {number}
  1206. * @constant
  1207. */
  1208. const EqualStencilFunc = 514;
  1209. /**
  1210. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1211. *
  1212. * @type {number}
  1213. * @constant
  1214. */
  1215. const LessEqualStencilFunc = 515;
  1216. /**
  1217. * Will return true if the stencil reference value is greater than the current stencil value.
  1218. *
  1219. * @type {number}
  1220. * @constant
  1221. */
  1222. const GreaterStencilFunc = 516;
  1223. /**
  1224. * Will return true if the stencil reference value is not equal to the current stencil value.
  1225. *
  1226. * @type {number}
  1227. * @constant
  1228. */
  1229. const NotEqualStencilFunc = 517;
  1230. /**
  1231. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1232. *
  1233. * @type {number}
  1234. * @constant
  1235. */
  1236. const GreaterEqualStencilFunc = 518;
  1237. /**
  1238. * Will always return true.
  1239. *
  1240. * @type {number}
  1241. * @constant
  1242. */
  1243. const AlwaysStencilFunc = 519;
  1244. /**
  1245. * Never pass.
  1246. *
  1247. * @type {number}
  1248. * @constant
  1249. */
  1250. const NeverCompare = 512;
  1251. /**
  1252. * Pass if the incoming value is less than the texture value.
  1253. *
  1254. * @type {number}
  1255. * @constant
  1256. */
  1257. const LessCompare = 513;
  1258. /**
  1259. * Pass if the incoming value equals the texture value.
  1260. *
  1261. * @type {number}
  1262. * @constant
  1263. */
  1264. const EqualCompare = 514;
  1265. /**
  1266. * Pass if the incoming value is less than or equal to the texture value.
  1267. *
  1268. * @type {number}
  1269. * @constant
  1270. */
  1271. const LessEqualCompare = 515;
  1272. /**
  1273. * Pass if the incoming value is greater than the texture value.
  1274. *
  1275. * @type {number}
  1276. * @constant
  1277. */
  1278. const GreaterCompare = 516;
  1279. /**
  1280. * Pass if the incoming value is not equal to the texture value.
  1281. *
  1282. * @type {number}
  1283. * @constant
  1284. */
  1285. const NotEqualCompare = 517;
  1286. /**
  1287. * Pass if the incoming value is greater than or equal to the texture value.
  1288. *
  1289. * @type {number}
  1290. * @constant
  1291. */
  1292. const GreaterEqualCompare = 518;
  1293. /**
  1294. * Always pass.
  1295. *
  1296. * @type {number}
  1297. * @constant
  1298. */
  1299. const AlwaysCompare = 519;
  1300. /**
  1301. * The contents are intended to be specified once by the application, and used many
  1302. * times as the source for drawing and image specification commands.
  1303. *
  1304. * @type {number}
  1305. * @constant
  1306. */
  1307. const StaticDrawUsage = 35044;
  1308. /**
  1309. * The contents are intended to be respecified repeatedly by the application, and
  1310. * used many times as the source for drawing and image specification commands.
  1311. *
  1312. * @type {number}
  1313. * @constant
  1314. */
  1315. const DynamicDrawUsage = 35048;
  1316. /**
  1317. * The contents are intended to be specified once by the application, and used at most
  1318. * a few times as the source for drawing and image specification commands.
  1319. *
  1320. * @type {number}
  1321. * @constant
  1322. */
  1323. const StreamDrawUsage = 35040;
  1324. /**
  1325. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1326. * many times by the application.
  1327. *
  1328. * @type {number}
  1329. * @constant
  1330. */
  1331. const StaticReadUsage = 35045;
  1332. /**
  1333. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1334. * many times by the application.
  1335. *
  1336. * @type {number}
  1337. * @constant
  1338. */
  1339. const DynamicReadUsage = 35049;
  1340. /**
  1341. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1342. * a few times by the application
  1343. *
  1344. * @type {number}
  1345. * @constant
  1346. */
  1347. const StreamReadUsage = 35041;
  1348. /**
  1349. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1350. * the source for WebGL drawing and image specification commands.
  1351. *
  1352. * @type {number}
  1353. * @constant
  1354. */
  1355. const StaticCopyUsage = 35046;
  1356. /**
  1357. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1358. * as the source for WebGL drawing and image specification commands.
  1359. *
  1360. * @type {number}
  1361. * @constant
  1362. */
  1363. const DynamicCopyUsage = 35050;
  1364. /**
  1365. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1366. * as the source for WebGL drawing and image specification commands.
  1367. *
  1368. * @type {number}
  1369. * @constant
  1370. */
  1371. const StreamCopyUsage = 35042;
  1372. /**
  1373. * GLSL 1 shader code.
  1374. *
  1375. * @type {string}
  1376. * @constant
  1377. */
  1378. const GLSL1 = '100';
  1379. /**
  1380. * GLSL 3 shader code.
  1381. *
  1382. * @type {string}
  1383. * @constant
  1384. */
  1385. const GLSL3 = '300 es';
  1386. /**
  1387. * WebGL coordinate system.
  1388. *
  1389. * @type {number}
  1390. * @constant
  1391. */
  1392. const WebGLCoordinateSystem = 2000;
  1393. /**
  1394. * WebGPU coordinate system.
  1395. *
  1396. * @type {number}
  1397. * @constant
  1398. */
  1399. const WebGPUCoordinateSystem = 2001;
  1400. /**
  1401. * Represents the different timestamp query types.
  1402. *
  1403. * @type {ConstantsTimestampQuery}
  1404. * @constant
  1405. */
  1406. const TimestampQuery = {
  1407. COMPUTE: 'compute',
  1408. RENDER: 'render'
  1409. };
  1410. /**
  1411. * Represents mouse buttons and interaction types in context of controls.
  1412. *
  1413. * @type {ConstantsInterpolationSamplingType}
  1414. * @constant
  1415. */
  1416. const InterpolationSamplingType = {
  1417. PERSPECTIVE: 'perspective',
  1418. LINEAR: 'linear',
  1419. FLAT: 'flat'
  1420. };
  1421. /**
  1422. * Represents the different interpolation sampling modes.
  1423. *
  1424. * @type {ConstantsInterpolationSamplingMode}
  1425. * @constant
  1426. */
  1427. const InterpolationSamplingMode = {
  1428. NORMAL: 'normal',
  1429. CENTROID: 'centroid',
  1430. SAMPLE: 'sample',
  1431. FIRST: 'first',
  1432. EITHER: 'either'
  1433. };
  1434. /**
  1435. * This type represents mouse buttons and interaction types in context of controls.
  1436. *
  1437. * @typedef {Object} ConstantsMouse
  1438. * @property {number} MIDDLE - The left mouse button.
  1439. * @property {number} LEFT - The middle mouse button.
  1440. * @property {number} RIGHT - The right mouse button.
  1441. * @property {number} ROTATE - A rotate interaction.
  1442. * @property {number} DOLLY - A dolly interaction.
  1443. * @property {number} PAN - A pan interaction.
  1444. **/
  1445. /**
  1446. * This type represents touch interaction types in context of controls.
  1447. *
  1448. * @typedef {Object} ConstantsTouch
  1449. * @property {number} ROTATE - A rotate interaction.
  1450. * @property {number} PAN - A pan interaction.
  1451. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1452. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1453. **/
  1454. /**
  1455. * This type represents the different timestamp query types.
  1456. *
  1457. * @typedef {Object} ConstantsTimestampQuery
  1458. * @property {string} COMPUTE - A `compute` timestamp query.
  1459. * @property {string} RENDER - A `render` timestamp query.
  1460. **/
  1461. /**
  1462. * Represents the different interpolation sampling types.
  1463. *
  1464. * @typedef {Object} ConstantsInterpolationSamplingType
  1465. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1466. * @property {string} LINEAR - Linear interpolation.
  1467. * @property {string} FLAT - Flat interpolation.
  1468. */
  1469. /**
  1470. * Represents the different interpolation sampling modes.
  1471. *
  1472. * @typedef {Object} ConstantsInterpolationSamplingMode
  1473. * @property {string} NORMAL - Normal sampling mode.
  1474. * @property {string} CENTROID - Centroid sampling mode.
  1475. * @property {string} SAMPLE - Sample-specific sampling mode.
  1476. * @property {string} FLAT_FIRST - Flat interpolation using the first vertex.
  1477. * @property {string} FLAT_EITHER - Flat interpolation using either vertex.
  1478. */
  1479. /**
  1480. * This modules allows to dispatch event objects on custom JavaScript objects.
  1481. *
  1482. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  1483. *
  1484. * Code Example:
  1485. * ```js
  1486. * class Car extends EventDispatcher {
  1487. * start() {
  1488. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1489. * }
  1490. *};
  1491. *
  1492. * // Using events with the custom object
  1493. * const car = new Car();
  1494. * car.addEventListener( 'start', function ( event ) {
  1495. * alert( event.message );
  1496. * } );
  1497. *
  1498. * car.start();
  1499. * ```
  1500. */
  1501. class EventDispatcher {
  1502. /**
  1503. * Adds the given event listener to the given event type.
  1504. *
  1505. * @param {string} type - The type of event to listen to.
  1506. * @param {Function} listener - The function that gets called when the event is fired.
  1507. */
  1508. addEventListener( type, listener ) {
  1509. if ( this._listeners === undefined ) this._listeners = {};
  1510. const listeners = this._listeners;
  1511. if ( listeners[ type ] === undefined ) {
  1512. listeners[ type ] = [];
  1513. }
  1514. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1515. listeners[ type ].push( listener );
  1516. }
  1517. }
  1518. /**
  1519. * Returns `true` if the given event listener has been added to the given event type.
  1520. *
  1521. * @param {string} type - The type of event.
  1522. * @param {Function} listener - The listener to check.
  1523. * @return {boolean} Whether the given event listener has been added to the given event type.
  1524. */
  1525. hasEventListener( type, listener ) {
  1526. const listeners = this._listeners;
  1527. if ( listeners === undefined ) return false;
  1528. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1529. }
  1530. /**
  1531. * Removes the given event listener from the given event type.
  1532. *
  1533. * @param {string} type - The type of event.
  1534. * @param {Function} listener - The listener to remove.
  1535. */
  1536. removeEventListener( type, listener ) {
  1537. const listeners = this._listeners;
  1538. if ( listeners === undefined ) return;
  1539. const listenerArray = listeners[ type ];
  1540. if ( listenerArray !== undefined ) {
  1541. const index = listenerArray.indexOf( listener );
  1542. if ( index !== -1 ) {
  1543. listenerArray.splice( index, 1 );
  1544. }
  1545. }
  1546. }
  1547. /**
  1548. * Dispatches an event object.
  1549. *
  1550. * @param {Object} event - The event that gets fired.
  1551. */
  1552. dispatchEvent( event ) {
  1553. const listeners = this._listeners;
  1554. if ( listeners === undefined ) return;
  1555. const listenerArray = listeners[ event.type ];
  1556. if ( listenerArray !== undefined ) {
  1557. event.target = this;
  1558. // Make a copy, in case listeners are removed while iterating.
  1559. const array = listenerArray.slice( 0 );
  1560. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1561. array[ i ].call( this, event );
  1562. }
  1563. event.target = null;
  1564. }
  1565. }
  1566. }
  1567. 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' ];
  1568. let _seed = 1234567;
  1569. const DEG2RAD = Math.PI / 180;
  1570. const RAD2DEG = 180 / Math.PI;
  1571. /**
  1572. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1573. * (universally unique identifier).
  1574. *
  1575. * @return {string} The UUID.
  1576. */
  1577. function generateUUID() {
  1578. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1579. const d0 = Math.random() * 0xffffffff | 0;
  1580. const d1 = Math.random() * 0xffffffff | 0;
  1581. const d2 = Math.random() * 0xffffffff | 0;
  1582. const d3 = Math.random() * 0xffffffff | 0;
  1583. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1584. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1585. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1586. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1587. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1588. return uuid.toLowerCase();
  1589. }
  1590. /**
  1591. * Clamps the given value between min and max.
  1592. *
  1593. * @param {number} value - The value to clamp.
  1594. * @param {number} min - The min value.
  1595. * @param {number} max - The max value.
  1596. * @return {number} The clamped value.
  1597. */
  1598. function clamp( value, min, max ) {
  1599. return Math.max( min, Math.min( max, value ) );
  1600. }
  1601. /**
  1602. * Computes the Euclidean modulo of the given parameters that
  1603. * is `( ( n % m ) + m ) % m`.
  1604. *
  1605. * @param {number} n - The first parameter.
  1606. * @param {number} m - The second parameter.
  1607. * @return {number} The Euclidean modulo.
  1608. */
  1609. function euclideanModulo( n, m ) {
  1610. // https://en.wikipedia.org/wiki/Modulo_operation
  1611. return ( ( n % m ) + m ) % m;
  1612. }
  1613. /**
  1614. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1615. * for the given value.
  1616. *
  1617. * @param {number} x - The value to be mapped.
  1618. * @param {number} a1 - Minimum value for range A.
  1619. * @param {number} a2 - Maximum value for range A.
  1620. * @param {number} b1 - Minimum value for range B.
  1621. * @param {number} b2 - Maximum value for range B.
  1622. * @return {number} The mapped value.
  1623. */
  1624. function mapLinear( x, a1, a2, b1, b2 ) {
  1625. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1626. }
  1627. /**
  1628. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1629. * between the start and end point.
  1630. *
  1631. * @param {number} x - The start point
  1632. * @param {number} y - The end point.
  1633. * @param {number} value - A value between start and end.
  1634. * @return {number} The interpolation factor.
  1635. */
  1636. function inverseLerp( x, y, value ) {
  1637. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1638. if ( x !== y ) {
  1639. return ( value - x ) / ( y - x );
  1640. } else {
  1641. return 0;
  1642. }
  1643. }
  1644. /**
  1645. * Returns a value linearly interpolated from two known points based on the given interval -
  1646. * `t = 0` will return `x` and `t = 1` will return `y`.
  1647. *
  1648. * @param {number} x - The start point
  1649. * @param {number} y - The end point.
  1650. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1651. * @return {number} The interpolated value.
  1652. */
  1653. function lerp( x, y, t ) {
  1654. return ( 1 - t ) * x + t * y;
  1655. }
  1656. /**
  1657. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1658. * time to maintain frame rate independent movement. For details, see
  1659. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1660. *
  1661. * @param {number} x - The current point.
  1662. * @param {number} y - The target point.
  1663. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1664. * and a lower value will make the movement more gradual.
  1665. * @param {number} dt - Delta time in seconds.
  1666. * @return {number} The interpolated value.
  1667. */
  1668. function damp( x, y, lambda, dt ) {
  1669. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1670. }
  1671. /**
  1672. * Returns a value that alternates between `0` and the given `length` parameter.
  1673. *
  1674. * @param {number} x - The value to pingpong.
  1675. * @param {number} [length=1] - The positive value the function will pingpong to.
  1676. * @return {number} The alternated value.
  1677. */
  1678. function pingpong( x, length = 1 ) {
  1679. // https://www.desmos.com/calculator/vcsjnyz7x4
  1680. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1681. }
  1682. /**
  1683. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1684. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1685. * the `min` and `max`.
  1686. *
  1687. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  1688. *
  1689. * @param {number} x - The value to evaluate based on its position between min and max.
  1690. * @param {number} min - The min value. Any x value below min will be `0`.
  1691. * @param {number} max - The max value. Any x value above max will be `1`.
  1692. * @return {number} The alternated value.
  1693. */
  1694. function smoothstep( x, min, max ) {
  1695. if ( x <= min ) return 0;
  1696. if ( x >= max ) return 1;
  1697. x = ( x - min ) / ( max - min );
  1698. return x * x * ( 3 - 2 * x );
  1699. }
  1700. /**
  1701. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  1702. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1703. *
  1704. * @param {number} x - The value to evaluate based on its position between min and max.
  1705. * @param {number} min - The min value. Any x value below min will be `0`.
  1706. * @param {number} max - The max value. Any x value above max will be `1`.
  1707. * @return {number} The alternated value.
  1708. */
  1709. function smootherstep( x, min, max ) {
  1710. if ( x <= min ) return 0;
  1711. if ( x >= max ) return 1;
  1712. x = ( x - min ) / ( max - min );
  1713. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1714. }
  1715. /**
  1716. * Returns a random integer from `<low, high>` interval.
  1717. *
  1718. * @param {number} low - The lower value boundary.
  1719. * @param {number} high - The upper value boundary
  1720. * @return {number} A random integer.
  1721. */
  1722. function randInt( low, high ) {
  1723. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1724. }
  1725. /**
  1726. * Returns a random float from `<low, high>` interval.
  1727. *
  1728. * @param {number} low - The lower value boundary.
  1729. * @param {number} high - The upper value boundary
  1730. * @return {number} A random float.
  1731. */
  1732. function randFloat( low, high ) {
  1733. return low + Math.random() * ( high - low );
  1734. }
  1735. /**
  1736. * Returns a random integer from `<-range/2, range/2>` interval.
  1737. *
  1738. * @param {number} range - Defines the value range.
  1739. * @return {number} A random float.
  1740. */
  1741. function randFloatSpread( range ) {
  1742. return range * ( 0.5 - Math.random() );
  1743. }
  1744. /**
  1745. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1746. *
  1747. * @param {number} [s] - The integer seed.
  1748. * @return {number} A random float.
  1749. */
  1750. function seededRandom( s ) {
  1751. if ( s !== undefined ) _seed = s;
  1752. // Mulberry32 generator
  1753. let t = _seed += 0x6D2B79F5;
  1754. t = Math.imul( t ^ t >>> 15, t | 1 );
  1755. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1756. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1757. }
  1758. /**
  1759. * Converts degrees to radians.
  1760. *
  1761. * @param {number} degrees - A value in degrees.
  1762. * @return {number} The converted value in radians.
  1763. */
  1764. function degToRad( degrees ) {
  1765. return degrees * DEG2RAD;
  1766. }
  1767. /**
  1768. * Converts radians to degrees.
  1769. *
  1770. * @param {number} radians - A value in radians.
  1771. * @return {number} The converted value in degrees.
  1772. */
  1773. function radToDeg( radians ) {
  1774. return radians * RAD2DEG;
  1775. }
  1776. /**
  1777. * Returns `true` if the given number is a power of two.
  1778. *
  1779. * @param {number} value - The value to check.
  1780. * @return {boolean} Whether the given number is a power of two or not.
  1781. */
  1782. function isPowerOfTwo( value ) {
  1783. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1784. }
  1785. /**
  1786. * Returns the smallest power of two that is greater than or equal to the given number.
  1787. *
  1788. * @param {number} value - The value to find a POT for.
  1789. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1790. */
  1791. function ceilPowerOfTwo( value ) {
  1792. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1793. }
  1794. /**
  1795. * Returns the largest power of two that is less than or equal to the given number.
  1796. *
  1797. * @param {number} value - The value to find a POT for.
  1798. * @return {number} The largest power of two that is less than or equal to the given number.
  1799. */
  1800. function floorPowerOfTwo( value ) {
  1801. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1802. }
  1803. /**
  1804. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  1805. * defined by the given angles and order.
  1806. *
  1807. * Rotations are applied to the axes in the order specified by order:
  1808. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1809. *
  1810. * @param {Quaternion} q - The quaternion to set.
  1811. * @param {number} a - The rotation applied to the first axis, in radians.
  1812. * @param {number} b - The rotation applied to the second axis, in radians.
  1813. * @param {number} c - The rotation applied to the third axis, in radians.
  1814. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1815. */
  1816. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1817. const cos = Math.cos;
  1818. const sin = Math.sin;
  1819. const c2 = cos( b / 2 );
  1820. const s2 = sin( b / 2 );
  1821. const c13 = cos( ( a + c ) / 2 );
  1822. const s13 = sin( ( a + c ) / 2 );
  1823. const c1_3 = cos( ( a - c ) / 2 );
  1824. const s1_3 = sin( ( a - c ) / 2 );
  1825. const c3_1 = cos( ( c - a ) / 2 );
  1826. const s3_1 = sin( ( c - a ) / 2 );
  1827. switch ( order ) {
  1828. case 'XYX':
  1829. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1830. break;
  1831. case 'YZY':
  1832. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1833. break;
  1834. case 'ZXZ':
  1835. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1836. break;
  1837. case 'XZX':
  1838. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1839. break;
  1840. case 'YXY':
  1841. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1842. break;
  1843. case 'ZYZ':
  1844. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1845. break;
  1846. default:
  1847. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1848. }
  1849. }
  1850. /**
  1851. * Denormalizes the given value according to the given typed array.
  1852. *
  1853. * @param {number} value - The value to denormalize.
  1854. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1855. * @return {number} The denormalize (float) value in the range `[0,1]`.
  1856. */
  1857. function denormalize( value, array ) {
  1858. switch ( array.constructor ) {
  1859. case Float32Array:
  1860. return value;
  1861. case Uint32Array:
  1862. return value / 4294967295.0;
  1863. case Uint16Array:
  1864. return value / 65535.0;
  1865. case Uint8Array:
  1866. return value / 255.0;
  1867. case Int32Array:
  1868. return Math.max( value / 2147483647.0, -1 );
  1869. case Int16Array:
  1870. return Math.max( value / 32767.0, -1 );
  1871. case Int8Array:
  1872. return Math.max( value / 127.0, -1 );
  1873. default:
  1874. throw new Error( 'Invalid component type.' );
  1875. }
  1876. }
  1877. /**
  1878. * Normalizes the given value according to the given typed array.
  1879. *
  1880. * @param {number} value - The float value in the range `[0,1]` to normalize.
  1881. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1882. * @return {number} The normalize value.
  1883. */
  1884. function normalize( value, array ) {
  1885. switch ( array.constructor ) {
  1886. case Float32Array:
  1887. return value;
  1888. case Uint32Array:
  1889. return Math.round( value * 4294967295.0 );
  1890. case Uint16Array:
  1891. return Math.round( value * 65535.0 );
  1892. case Uint8Array:
  1893. return Math.round( value * 255.0 );
  1894. case Int32Array:
  1895. return Math.round( value * 2147483647.0 );
  1896. case Int16Array:
  1897. return Math.round( value * 32767.0 );
  1898. case Int8Array:
  1899. return Math.round( value * 127.0 );
  1900. default:
  1901. throw new Error( 'Invalid component type.' );
  1902. }
  1903. }
  1904. /**
  1905. * @class
  1906. * @classdesc A collection of math utility functions.
  1907. * @hideconstructor
  1908. */
  1909. const MathUtils = {
  1910. DEG2RAD: DEG2RAD,
  1911. RAD2DEG: RAD2DEG,
  1912. /**
  1913. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1914. * (universally unique identifier).
  1915. *
  1916. * @static
  1917. * @method
  1918. * @return {string} The UUID.
  1919. */
  1920. generateUUID: generateUUID,
  1921. /**
  1922. * Clamps the given value between min and max.
  1923. *
  1924. * @static
  1925. * @method
  1926. * @param {number} value - The value to clamp.
  1927. * @param {number} min - The min value.
  1928. * @param {number} max - The max value.
  1929. * @return {number} The clamped value.
  1930. */
  1931. clamp: clamp,
  1932. /**
  1933. * Computes the Euclidean modulo of the given parameters that
  1934. * is `( ( n % m ) + m ) % m`.
  1935. *
  1936. * @static
  1937. * @method
  1938. * @param {number} n - The first parameter.
  1939. * @param {number} m - The second parameter.
  1940. * @return {number} The Euclidean modulo.
  1941. */
  1942. euclideanModulo: euclideanModulo,
  1943. /**
  1944. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1945. * for the given value.
  1946. *
  1947. * @static
  1948. * @method
  1949. * @param {number} x - The value to be mapped.
  1950. * @param {number} a1 - Minimum value for range A.
  1951. * @param {number} a2 - Maximum value for range A.
  1952. * @param {number} b1 - Minimum value for range B.
  1953. * @param {number} b2 - Maximum value for range B.
  1954. * @return {number} The mapped value.
  1955. */
  1956. mapLinear: mapLinear,
  1957. /**
  1958. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1959. * between the start and end point.
  1960. *
  1961. * @static
  1962. * @method
  1963. * @param {number} x - The start point
  1964. * @param {number} y - The end point.
  1965. * @param {number} value - A value between start and end.
  1966. * @return {number} The interpolation factor.
  1967. */
  1968. inverseLerp: inverseLerp,
  1969. /**
  1970. * Returns a value linearly interpolated from two known points based on the given interval -
  1971. * `t = 0` will return `x` and `t = 1` will return `y`.
  1972. *
  1973. * @static
  1974. * @method
  1975. * @param {number} x - The start point
  1976. * @param {number} y - The end point.
  1977. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1978. * @return {number} The interpolated value.
  1979. */
  1980. lerp: lerp,
  1981. /**
  1982. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1983. * time to maintain frame rate independent movement. For details, see
  1984. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1985. *
  1986. * @static
  1987. * @method
  1988. * @param {number} x - The current point.
  1989. * @param {number} y - The target point.
  1990. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1991. * and a lower value will make the movement more gradual.
  1992. * @param {number} dt - Delta time in seconds.
  1993. * @return {number} The interpolated value.
  1994. */
  1995. damp: damp,
  1996. /**
  1997. * Returns a value that alternates between `0` and the given `length` parameter.
  1998. *
  1999. * @static
  2000. * @method
  2001. * @param {number} x - The value to pingpong.
  2002. * @param {number} [length=1] - The positive value the function will pingpong to.
  2003. * @return {number} The alternated value.
  2004. */
  2005. pingpong: pingpong,
  2006. /**
  2007. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2008. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2009. * the `min` and `max`.
  2010. *
  2011. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  2012. *
  2013. * @static
  2014. * @method
  2015. * @param {number} x - The value to evaluate based on its position between min and max.
  2016. * @param {number} min - The min value. Any x value below min will be `0`.
  2017. * @param {number} max - The max value. Any x value above max will be `1`.
  2018. * @return {number} The alternated value.
  2019. */
  2020. smoothstep: smoothstep,
  2021. /**
  2022. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  2023. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2024. *
  2025. * @static
  2026. * @method
  2027. * @param {number} x - The value to evaluate based on its position between min and max.
  2028. * @param {number} min - The min value. Any x value below min will be `0`.
  2029. * @param {number} max - The max value. Any x value above max will be `1`.
  2030. * @return {number} The alternated value.
  2031. */
  2032. smootherstep: smootherstep,
  2033. /**
  2034. * Returns a random integer from `<low, high>` interval.
  2035. *
  2036. * @static
  2037. * @method
  2038. * @param {number} low - The lower value boundary.
  2039. * @param {number} high - The upper value boundary
  2040. * @return {number} A random integer.
  2041. */
  2042. randInt: randInt,
  2043. /**
  2044. * Returns a random float from `<low, high>` interval.
  2045. *
  2046. * @static
  2047. * @method
  2048. * @param {number} low - The lower value boundary.
  2049. * @param {number} high - The upper value boundary
  2050. * @return {number} A random float.
  2051. */
  2052. randFloat: randFloat,
  2053. /**
  2054. * Returns a random integer from `<-range/2, range/2>` interval.
  2055. *
  2056. * @static
  2057. * @method
  2058. * @param {number} range - Defines the value range.
  2059. * @return {number} A random float.
  2060. */
  2061. randFloatSpread: randFloatSpread,
  2062. /**
  2063. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2064. *
  2065. * @static
  2066. * @method
  2067. * @param {number} [s] - The integer seed.
  2068. * @return {number} A random float.
  2069. */
  2070. seededRandom: seededRandom,
  2071. /**
  2072. * Converts degrees to radians.
  2073. *
  2074. * @static
  2075. * @method
  2076. * @param {number} degrees - A value in degrees.
  2077. * @return {number} The converted value in radians.
  2078. */
  2079. degToRad: degToRad,
  2080. /**
  2081. * Converts radians to degrees.
  2082. *
  2083. * @static
  2084. * @method
  2085. * @param {number} radians - A value in radians.
  2086. * @return {number} The converted value in degrees.
  2087. */
  2088. radToDeg: radToDeg,
  2089. /**
  2090. * Returns `true` if the given number is a power of two.
  2091. *
  2092. * @static
  2093. * @method
  2094. * @param {number} value - The value to check.
  2095. * @return {boolean} Whether the given number is a power of two or not.
  2096. */
  2097. isPowerOfTwo: isPowerOfTwo,
  2098. /**
  2099. * Returns the smallest power of two that is greater than or equal to the given number.
  2100. *
  2101. * @static
  2102. * @method
  2103. * @param {number} value - The value to find a POT for.
  2104. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2105. */
  2106. ceilPowerOfTwo: ceilPowerOfTwo,
  2107. /**
  2108. * Returns the largest power of two that is less than or equal to the given number.
  2109. *
  2110. * @static
  2111. * @method
  2112. * @param {number} value - The value to find a POT for.
  2113. * @return {number} The largest power of two that is less than or equal to the given number.
  2114. */
  2115. floorPowerOfTwo: floorPowerOfTwo,
  2116. /**
  2117. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  2118. * defined by the given angles and order.
  2119. *
  2120. * Rotations are applied to the axes in the order specified by order:
  2121. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2122. *
  2123. * @static
  2124. * @method
  2125. * @param {Quaternion} q - The quaternion to set.
  2126. * @param {number} a - The rotation applied to the first axis, in radians.
  2127. * @param {number} b - The rotation applied to the second axis, in radians.
  2128. * @param {number} c - The rotation applied to the third axis, in radians.
  2129. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2130. */
  2131. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2132. /**
  2133. * Normalizes the given value according to the given typed array.
  2134. *
  2135. * @static
  2136. * @method
  2137. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2138. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2139. * @return {number} The normalize value.
  2140. */
  2141. normalize: normalize,
  2142. /**
  2143. * Denormalizes the given value according to the given typed array.
  2144. *
  2145. * @static
  2146. * @method
  2147. * @param {number} value - The value to denormalize.
  2148. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2149. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2150. */
  2151. denormalize: denormalize
  2152. };
  2153. /**
  2154. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2155. * (labeled x and y), which can be used to represent a number of things, such as:
  2156. *
  2157. * - A point in 2D space (i.e. a position on a plane).
  2158. * - A direction and length across a plane. In three.js the length will
  2159. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2160. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2161. * - Any arbitrary ordered pair of numbers.
  2162. *
  2163. * There are other things a 2D vector can be used to represent, such as
  2164. * momentum vectors, complex numbers and so on, however these are the most
  2165. * common uses in three.js.
  2166. *
  2167. * Iterating through a vector instance will yield its components `(x, y)` in
  2168. * the corresponding order.
  2169. * ```js
  2170. * const a = new THREE.Vector2( 0, 1 );
  2171. *
  2172. * //no arguments; will be initialised to (0, 0)
  2173. * const b = new THREE.Vector2( );
  2174. *
  2175. * const d = a.distanceTo( b );
  2176. * ```
  2177. */
  2178. class Vector2 {
  2179. /**
  2180. * Constructs a new 2D vector.
  2181. *
  2182. * @param {number} [x=0] - The x value of this vector.
  2183. * @param {number} [y=0] - The y value of this vector.
  2184. */
  2185. constructor( x = 0, y = 0 ) {
  2186. /**
  2187. * This flag can be used for type testing.
  2188. *
  2189. * @type {boolean}
  2190. * @readonly
  2191. * @default true
  2192. */
  2193. Vector2.prototype.isVector2 = true;
  2194. /**
  2195. * The x value of this vector.
  2196. *
  2197. * @type {number}
  2198. */
  2199. this.x = x;
  2200. /**
  2201. * The y value of this vector.
  2202. *
  2203. * @type {number}
  2204. */
  2205. this.y = y;
  2206. }
  2207. /**
  2208. * Alias for {@link Vector2#x}.
  2209. *
  2210. * @type {number}
  2211. */
  2212. get width() {
  2213. return this.x;
  2214. }
  2215. set width( value ) {
  2216. this.x = value;
  2217. }
  2218. /**
  2219. * Alias for {@link Vector2#y}.
  2220. *
  2221. * @type {number}
  2222. */
  2223. get height() {
  2224. return this.y;
  2225. }
  2226. set height( value ) {
  2227. this.y = value;
  2228. }
  2229. /**
  2230. * Sets the vector components.
  2231. *
  2232. * @param {number} x - The value of the x component.
  2233. * @param {number} y - The value of the y component.
  2234. * @return {Vector2} A reference to this vector.
  2235. */
  2236. set( x, y ) {
  2237. this.x = x;
  2238. this.y = y;
  2239. return this;
  2240. }
  2241. /**
  2242. * Sets the vector components to the same value.
  2243. *
  2244. * @param {number} scalar - The value to set for all vector components.
  2245. * @return {Vector2} A reference to this vector.
  2246. */
  2247. setScalar( scalar ) {
  2248. this.x = scalar;
  2249. this.y = scalar;
  2250. return this;
  2251. }
  2252. /**
  2253. * Sets the vector's x component to the given value
  2254. *
  2255. * @param {number} x - The value to set.
  2256. * @return {Vector2} A reference to this vector.
  2257. */
  2258. setX( x ) {
  2259. this.x = x;
  2260. return this;
  2261. }
  2262. /**
  2263. * Sets the vector's y component to the given value
  2264. *
  2265. * @param {number} y - The value to set.
  2266. * @return {Vector2} A reference to this vector.
  2267. */
  2268. setY( y ) {
  2269. this.y = y;
  2270. return this;
  2271. }
  2272. /**
  2273. * Allows to set a vector component with an index.
  2274. *
  2275. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2276. * @param {number} value - The value to set.
  2277. * @return {Vector2} A reference to this vector.
  2278. */
  2279. setComponent( index, value ) {
  2280. switch ( index ) {
  2281. case 0: this.x = value; break;
  2282. case 1: this.y = value; break;
  2283. default: throw new Error( 'index is out of range: ' + index );
  2284. }
  2285. return this;
  2286. }
  2287. /**
  2288. * Returns the value of the vector component which matches the given index.
  2289. *
  2290. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2291. * @return {number} A vector component value.
  2292. */
  2293. getComponent( index ) {
  2294. switch ( index ) {
  2295. case 0: return this.x;
  2296. case 1: return this.y;
  2297. default: throw new Error( 'index is out of range: ' + index );
  2298. }
  2299. }
  2300. /**
  2301. * Returns a new vector with copied values from this instance.
  2302. *
  2303. * @return {Vector2} A clone of this instance.
  2304. */
  2305. clone() {
  2306. return new this.constructor( this.x, this.y );
  2307. }
  2308. /**
  2309. * Copies the values of the given vector to this instance.
  2310. *
  2311. * @param {Vector2} v - The vector to copy.
  2312. * @return {Vector2} A reference to this vector.
  2313. */
  2314. copy( v ) {
  2315. this.x = v.x;
  2316. this.y = v.y;
  2317. return this;
  2318. }
  2319. /**
  2320. * Adds the given vector to this instance.
  2321. *
  2322. * @param {Vector2} v - The vector to add.
  2323. * @return {Vector2} A reference to this vector.
  2324. */
  2325. add( v ) {
  2326. this.x += v.x;
  2327. this.y += v.y;
  2328. return this;
  2329. }
  2330. /**
  2331. * Adds the given scalar value to all components of this instance.
  2332. *
  2333. * @param {number} s - The scalar to add.
  2334. * @return {Vector2} A reference to this vector.
  2335. */
  2336. addScalar( s ) {
  2337. this.x += s;
  2338. this.y += s;
  2339. return this;
  2340. }
  2341. /**
  2342. * Adds the given vectors and stores the result in this instance.
  2343. *
  2344. * @param {Vector2} a - The first vector.
  2345. * @param {Vector2} b - The second vector.
  2346. * @return {Vector2} A reference to this vector.
  2347. */
  2348. addVectors( a, b ) {
  2349. this.x = a.x + b.x;
  2350. this.y = a.y + b.y;
  2351. return this;
  2352. }
  2353. /**
  2354. * Adds the given vector scaled by the given factor to this instance.
  2355. *
  2356. * @param {Vector2} v - The vector.
  2357. * @param {number} s - The factor that scales `v`.
  2358. * @return {Vector2} A reference to this vector.
  2359. */
  2360. addScaledVector( v, s ) {
  2361. this.x += v.x * s;
  2362. this.y += v.y * s;
  2363. return this;
  2364. }
  2365. /**
  2366. * Subtracts the given vector from this instance.
  2367. *
  2368. * @param {Vector2} v - The vector to subtract.
  2369. * @return {Vector2} A reference to this vector.
  2370. */
  2371. sub( v ) {
  2372. this.x -= v.x;
  2373. this.y -= v.y;
  2374. return this;
  2375. }
  2376. /**
  2377. * Subtracts the given scalar value from all components of this instance.
  2378. *
  2379. * @param {number} s - The scalar to subtract.
  2380. * @return {Vector2} A reference to this vector.
  2381. */
  2382. subScalar( s ) {
  2383. this.x -= s;
  2384. this.y -= s;
  2385. return this;
  2386. }
  2387. /**
  2388. * Subtracts the given vectors and stores the result in this instance.
  2389. *
  2390. * @param {Vector2} a - The first vector.
  2391. * @param {Vector2} b - The second vector.
  2392. * @return {Vector2} A reference to this vector.
  2393. */
  2394. subVectors( a, b ) {
  2395. this.x = a.x - b.x;
  2396. this.y = a.y - b.y;
  2397. return this;
  2398. }
  2399. /**
  2400. * Multiplies the given vector with this instance.
  2401. *
  2402. * @param {Vector2} v - The vector to multiply.
  2403. * @return {Vector2} A reference to this vector.
  2404. */
  2405. multiply( v ) {
  2406. this.x *= v.x;
  2407. this.y *= v.y;
  2408. return this;
  2409. }
  2410. /**
  2411. * Multiplies the given scalar value with all components of this instance.
  2412. *
  2413. * @param {number} scalar - The scalar to multiply.
  2414. * @return {Vector2} A reference to this vector.
  2415. */
  2416. multiplyScalar( scalar ) {
  2417. this.x *= scalar;
  2418. this.y *= scalar;
  2419. return this;
  2420. }
  2421. /**
  2422. * Divides this instance by the given vector.
  2423. *
  2424. * @param {Vector2} v - The vector to divide.
  2425. * @return {Vector2} A reference to this vector.
  2426. */
  2427. divide( v ) {
  2428. this.x /= v.x;
  2429. this.y /= v.y;
  2430. return this;
  2431. }
  2432. /**
  2433. * Divides this vector by the given scalar.
  2434. *
  2435. * @param {number} scalar - The scalar to divide.
  2436. * @return {Vector2} A reference to this vector.
  2437. */
  2438. divideScalar( scalar ) {
  2439. return this.multiplyScalar( 1 / scalar );
  2440. }
  2441. /**
  2442. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2443. * the given 3x3 matrix.
  2444. *
  2445. * @param {Matrix3} m - The matrix to apply.
  2446. * @return {Vector2} A reference to this vector.
  2447. */
  2448. applyMatrix3( m ) {
  2449. const x = this.x, y = this.y;
  2450. const e = m.elements;
  2451. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2452. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2453. return this;
  2454. }
  2455. /**
  2456. * If this vector's x or y value is greater than the given vector's x or y
  2457. * value, replace that value with the corresponding min value.
  2458. *
  2459. * @param {Vector2} v - The vector.
  2460. * @return {Vector2} A reference to this vector.
  2461. */
  2462. min( v ) {
  2463. this.x = Math.min( this.x, v.x );
  2464. this.y = Math.min( this.y, v.y );
  2465. return this;
  2466. }
  2467. /**
  2468. * If this vector's x or y value is less than the given vector's x or y
  2469. * value, replace that value with the corresponding max value.
  2470. *
  2471. * @param {Vector2} v - The vector.
  2472. * @return {Vector2} A reference to this vector.
  2473. */
  2474. max( v ) {
  2475. this.x = Math.max( this.x, v.x );
  2476. this.y = Math.max( this.y, v.y );
  2477. return this;
  2478. }
  2479. /**
  2480. * If this vector's x or y value is greater than the max vector's x or y
  2481. * value, it is replaced by the corresponding value.
  2482. * If this vector's x or y value is less than the min vector's x or y value,
  2483. * it is replaced by the corresponding value.
  2484. *
  2485. * @param {Vector2} min - The minimum x and y values.
  2486. * @param {Vector2} max - The maximum x and y values in the desired range.
  2487. * @return {Vector2} A reference to this vector.
  2488. */
  2489. clamp( min, max ) {
  2490. // assumes min < max, componentwise
  2491. this.x = clamp( this.x, min.x, max.x );
  2492. this.y = clamp( this.y, min.y, max.y );
  2493. return this;
  2494. }
  2495. /**
  2496. * If this vector's x or y values are greater than the max value, they are
  2497. * replaced by the max value.
  2498. * If this vector's x or y values are less than the min value, they are
  2499. * replaced by the min value.
  2500. *
  2501. * @param {number} minVal - The minimum value the components will be clamped to.
  2502. * @param {number} maxVal - The maximum value the components will be clamped to.
  2503. * @return {Vector2} A reference to this vector.
  2504. */
  2505. clampScalar( minVal, maxVal ) {
  2506. this.x = clamp( this.x, minVal, maxVal );
  2507. this.y = clamp( this.y, minVal, maxVal );
  2508. return this;
  2509. }
  2510. /**
  2511. * If this vector's length is greater than the max value, it is replaced by
  2512. * the max value.
  2513. * If this vector's length is less than the min value, it is replaced by the
  2514. * min value.
  2515. *
  2516. * @param {number} min - The minimum value the vector length will be clamped to.
  2517. * @param {number} max - The maximum value the vector length will be clamped to.
  2518. * @return {Vector2} A reference to this vector.
  2519. */
  2520. clampLength( min, max ) {
  2521. const length = this.length();
  2522. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2523. }
  2524. /**
  2525. * The components of this vector are rounded down to the nearest integer value.
  2526. *
  2527. * @return {Vector2} A reference to this vector.
  2528. */
  2529. floor() {
  2530. this.x = Math.floor( this.x );
  2531. this.y = Math.floor( this.y );
  2532. return this;
  2533. }
  2534. /**
  2535. * The components of this vector are rounded up to the nearest integer value.
  2536. *
  2537. * @return {Vector2} A reference to this vector.
  2538. */
  2539. ceil() {
  2540. this.x = Math.ceil( this.x );
  2541. this.y = Math.ceil( this.y );
  2542. return this;
  2543. }
  2544. /**
  2545. * The components of this vector are rounded to the nearest integer value
  2546. *
  2547. * @return {Vector2} A reference to this vector.
  2548. */
  2549. round() {
  2550. this.x = Math.round( this.x );
  2551. this.y = Math.round( this.y );
  2552. return this;
  2553. }
  2554. /**
  2555. * The components of this vector are rounded towards zero (up if negative,
  2556. * down if positive) to an integer value.
  2557. *
  2558. * @return {Vector2} A reference to this vector.
  2559. */
  2560. roundToZero() {
  2561. this.x = Math.trunc( this.x );
  2562. this.y = Math.trunc( this.y );
  2563. return this;
  2564. }
  2565. /**
  2566. * Inverts this vector - i.e. sets x = -x and y = -y.
  2567. *
  2568. * @return {Vector2} A reference to this vector.
  2569. */
  2570. negate() {
  2571. this.x = - this.x;
  2572. this.y = - this.y;
  2573. return this;
  2574. }
  2575. /**
  2576. * Calculates the dot product of the given vector with this instance.
  2577. *
  2578. * @param {Vector2} v - The vector to compute the dot product with.
  2579. * @return {number} The result of the dot product.
  2580. */
  2581. dot( v ) {
  2582. return this.x * v.x + this.y * v.y;
  2583. }
  2584. /**
  2585. * Calculates the cross product of the given vector with this instance.
  2586. *
  2587. * @param {Vector2} v - The vector to compute the cross product with.
  2588. * @return {number} The result of the cross product.
  2589. */
  2590. cross( v ) {
  2591. return this.x * v.y - this.y * v.x;
  2592. }
  2593. /**
  2594. * Computes the square of the Euclidean length (straight-line length) from
  2595. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2596. * compare the length squared instead as it is slightly more efficient to calculate.
  2597. *
  2598. * @return {number} The square length of this vector.
  2599. */
  2600. lengthSq() {
  2601. return this.x * this.x + this.y * this.y;
  2602. }
  2603. /**
  2604. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2605. *
  2606. * @return {number} The length of this vector.
  2607. */
  2608. length() {
  2609. return Math.sqrt( this.x * this.x + this.y * this.y );
  2610. }
  2611. /**
  2612. * Computes the Manhattan length of this vector.
  2613. *
  2614. * @return {number} The length of this vector.
  2615. */
  2616. manhattanLength() {
  2617. return Math.abs( this.x ) + Math.abs( this.y );
  2618. }
  2619. /**
  2620. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2621. * with the same direction as this one, but with a vector length of `1`.
  2622. *
  2623. * @return {Vector2} A reference to this vector.
  2624. */
  2625. normalize() {
  2626. return this.divideScalar( this.length() || 1 );
  2627. }
  2628. /**
  2629. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2630. *
  2631. * @return {number} The angle in radians.
  2632. */
  2633. angle() {
  2634. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2635. return angle;
  2636. }
  2637. /**
  2638. * Returns the angle between the given vector and this instance in radians.
  2639. *
  2640. * @param {Vector2} v - The vector to compute the angle with.
  2641. * @return {number} The angle in radians.
  2642. */
  2643. angleTo( v ) {
  2644. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2645. if ( denominator === 0 ) return Math.PI / 2;
  2646. const theta = this.dot( v ) / denominator;
  2647. // clamp, to handle numerical problems
  2648. return Math.acos( clamp( theta, -1, 1 ) );
  2649. }
  2650. /**
  2651. * Computes the distance from the given vector to this instance.
  2652. *
  2653. * @param {Vector2} v - The vector to compute the distance to.
  2654. * @return {number} The distance.
  2655. */
  2656. distanceTo( v ) {
  2657. return Math.sqrt( this.distanceToSquared( v ) );
  2658. }
  2659. /**
  2660. * Computes the squared distance from the given vector to this instance.
  2661. * If you are just comparing the distance with another distance, you should compare
  2662. * the distance squared instead as it is slightly more efficient to calculate.
  2663. *
  2664. * @param {Vector2} v - The vector to compute the squared distance to.
  2665. * @return {number} The squared distance.
  2666. */
  2667. distanceToSquared( v ) {
  2668. const dx = this.x - v.x, dy = this.y - v.y;
  2669. return dx * dx + dy * dy;
  2670. }
  2671. /**
  2672. * Computes the Manhattan distance from the given vector to this instance.
  2673. *
  2674. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2675. * @return {number} The Manhattan distance.
  2676. */
  2677. manhattanDistanceTo( v ) {
  2678. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2679. }
  2680. /**
  2681. * Sets this vector to a vector with the same direction as this one, but
  2682. * with the specified length.
  2683. *
  2684. * @param {number} length - The new length of this vector.
  2685. * @return {Vector2} A reference to this vector.
  2686. */
  2687. setLength( length ) {
  2688. return this.normalize().multiplyScalar( length );
  2689. }
  2690. /**
  2691. * Linearly interpolates between the given vector and this instance, where
  2692. * alpha is the percent distance along the line - alpha = 0 will be this
  2693. * vector, and alpha = 1 will be the given one.
  2694. *
  2695. * @param {Vector2} v - The vector to interpolate towards.
  2696. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2697. * @return {Vector2} A reference to this vector.
  2698. */
  2699. lerp( v, alpha ) {
  2700. this.x += ( v.x - this.x ) * alpha;
  2701. this.y += ( v.y - this.y ) * alpha;
  2702. return this;
  2703. }
  2704. /**
  2705. * Linearly interpolates between the given vectors, where alpha is the percent
  2706. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2707. * be the second one. The result is stored in this instance.
  2708. *
  2709. * @param {Vector2} v1 - The first vector.
  2710. * @param {Vector2} v2 - The second vector.
  2711. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2712. * @return {Vector2} A reference to this vector.
  2713. */
  2714. lerpVectors( v1, v2, alpha ) {
  2715. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2716. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2717. return this;
  2718. }
  2719. /**
  2720. * Returns `true` if this vector is equal with the given one.
  2721. *
  2722. * @param {Vector2} v - The vector to test for equality.
  2723. * @return {boolean} Whether this vector is equal with the given one.
  2724. */
  2725. equals( v ) {
  2726. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2727. }
  2728. /**
  2729. * Sets this vector's x value to be `array[ offset ]` and y
  2730. * value to be `array[ offset + 1 ]`.
  2731. *
  2732. * @param {Array<number>} array - An array holding the vector component values.
  2733. * @param {number} [offset=0] - The offset into the array.
  2734. * @return {Vector2} A reference to this vector.
  2735. */
  2736. fromArray( array, offset = 0 ) {
  2737. this.x = array[ offset ];
  2738. this.y = array[ offset + 1 ];
  2739. return this;
  2740. }
  2741. /**
  2742. * Writes the components of this vector to the given array. If no array is provided,
  2743. * the method returns a new instance.
  2744. *
  2745. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2746. * @param {number} [offset=0] - Index of the first element in the array.
  2747. * @return {Array<number>} The vector components.
  2748. */
  2749. toArray( array = [], offset = 0 ) {
  2750. array[ offset ] = this.x;
  2751. array[ offset + 1 ] = this.y;
  2752. return array;
  2753. }
  2754. /**
  2755. * Sets the components of this vector from the given buffer attribute.
  2756. *
  2757. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2758. * @param {number} index - The index into the attribute.
  2759. * @return {Vector2} A reference to this vector.
  2760. */
  2761. fromBufferAttribute( attribute, index ) {
  2762. this.x = attribute.getX( index );
  2763. this.y = attribute.getY( index );
  2764. return this;
  2765. }
  2766. /**
  2767. * Rotates this vector around the given center by the given angle.
  2768. *
  2769. * @param {Vector2} center - The point around which to rotate.
  2770. * @param {number} angle - The angle to rotate, in radians.
  2771. * @return {Vector2} A reference to this vector.
  2772. */
  2773. rotateAround( center, angle ) {
  2774. const c = Math.cos( angle ), s = Math.sin( angle );
  2775. const x = this.x - center.x;
  2776. const y = this.y - center.y;
  2777. this.x = x * c - y * s + center.x;
  2778. this.y = x * s + y * c + center.y;
  2779. return this;
  2780. }
  2781. /**
  2782. * Sets each component of this vector to a pseudo-random value between `0` and
  2783. * `1`, excluding `1`.
  2784. *
  2785. * @return {Vector2} A reference to this vector.
  2786. */
  2787. random() {
  2788. this.x = Math.random();
  2789. this.y = Math.random();
  2790. return this;
  2791. }
  2792. *[ Symbol.iterator ]() {
  2793. yield this.x;
  2794. yield this.y;
  2795. }
  2796. }
  2797. /**
  2798. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2799. *
  2800. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2801. * the corresponding order.
  2802. *
  2803. * Note that three.js expects Quaternions to be normalized.
  2804. * ```js
  2805. * const quaternion = new THREE.Quaternion();
  2806. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2807. *
  2808. * const vector = new THREE.Vector3( 1, 0, 0 );
  2809. * vector.applyQuaternion( quaternion );
  2810. * ```
  2811. */
  2812. class Quaternion {
  2813. /**
  2814. * Constructs a new quaternion.
  2815. *
  2816. * @param {number} [x=0] - The x value of this quaternion.
  2817. * @param {number} [y=0] - The y value of this quaternion.
  2818. * @param {number} [z=0] - The z value of this quaternion.
  2819. * @param {number} [w=1] - The w value of this quaternion.
  2820. */
  2821. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2822. /**
  2823. * This flag can be used for type testing.
  2824. *
  2825. * @type {boolean}
  2826. * @readonly
  2827. * @default true
  2828. */
  2829. this.isQuaternion = true;
  2830. this._x = x;
  2831. this._y = y;
  2832. this._z = z;
  2833. this._w = w;
  2834. }
  2835. /**
  2836. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2837. * quaternion data are managed in flat arrays.
  2838. *
  2839. * @param {Array<number>} dst - The destination array.
  2840. * @param {number} dstOffset - An offset into the destination array.
  2841. * @param {Array<number>} src0 - The source array of the first quaternion.
  2842. * @param {number} srcOffset0 - An offset into the first source array.
  2843. * @param {Array<number>} src1 - The source array of the second quaternion.
  2844. * @param {number} srcOffset1 - An offset into the second source array.
  2845. * @param {number} t - The interpolation factor in the range `[0,1]`.
  2846. * @see {@link Quaternion#slerp}
  2847. */
  2848. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2849. // fuzz-free, array-based Quaternion SLERP operation
  2850. let x0 = src0[ srcOffset0 + 0 ],
  2851. y0 = src0[ srcOffset0 + 1 ],
  2852. z0 = src0[ srcOffset0 + 2 ],
  2853. w0 = src0[ srcOffset0 + 3 ];
  2854. const x1 = src1[ srcOffset1 + 0 ],
  2855. y1 = src1[ srcOffset1 + 1 ],
  2856. z1 = src1[ srcOffset1 + 2 ],
  2857. w1 = src1[ srcOffset1 + 3 ];
  2858. if ( t === 0 ) {
  2859. dst[ dstOffset + 0 ] = x0;
  2860. dst[ dstOffset + 1 ] = y0;
  2861. dst[ dstOffset + 2 ] = z0;
  2862. dst[ dstOffset + 3 ] = w0;
  2863. return;
  2864. }
  2865. if ( t === 1 ) {
  2866. dst[ dstOffset + 0 ] = x1;
  2867. dst[ dstOffset + 1 ] = y1;
  2868. dst[ dstOffset + 2 ] = z1;
  2869. dst[ dstOffset + 3 ] = w1;
  2870. return;
  2871. }
  2872. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2873. let s = 1 - t;
  2874. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2875. dir = ( cos >= 0 ? 1 : -1 ),
  2876. sqrSin = 1 - cos * cos;
  2877. // Skip the Slerp for tiny steps to avoid numeric problems:
  2878. if ( sqrSin > Number.EPSILON ) {
  2879. const sin = Math.sqrt( sqrSin ),
  2880. len = Math.atan2( sin, cos * dir );
  2881. s = Math.sin( s * len ) / sin;
  2882. t = Math.sin( t * len ) / sin;
  2883. }
  2884. const tDir = t * dir;
  2885. x0 = x0 * s + x1 * tDir;
  2886. y0 = y0 * s + y1 * tDir;
  2887. z0 = z0 * s + z1 * tDir;
  2888. w0 = w0 * s + w1 * tDir;
  2889. // Normalize in case we just did a lerp:
  2890. if ( s === 1 - t ) {
  2891. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2892. x0 *= f;
  2893. y0 *= f;
  2894. z0 *= f;
  2895. w0 *= f;
  2896. }
  2897. }
  2898. dst[ dstOffset ] = x0;
  2899. dst[ dstOffset + 1 ] = y0;
  2900. dst[ dstOffset + 2 ] = z0;
  2901. dst[ dstOffset + 3 ] = w0;
  2902. }
  2903. /**
  2904. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  2905. * in flat arrays.
  2906. *
  2907. * @param {Array<number>} dst - The destination array.
  2908. * @param {number} dstOffset - An offset into the destination array.
  2909. * @param {Array<number>} src0 - The source array of the first quaternion.
  2910. * @param {number} srcOffset0 - An offset into the first source array.
  2911. * @param {Array<number>} src1 - The source array of the second quaternion.
  2912. * @param {number} srcOffset1 - An offset into the second source array.
  2913. * @return {Array<number>} The destination array.
  2914. * @see {@link Quaternion#multiplyQuaternions}.
  2915. */
  2916. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2917. const x0 = src0[ srcOffset0 ];
  2918. const y0 = src0[ srcOffset0 + 1 ];
  2919. const z0 = src0[ srcOffset0 + 2 ];
  2920. const w0 = src0[ srcOffset0 + 3 ];
  2921. const x1 = src1[ srcOffset1 ];
  2922. const y1 = src1[ srcOffset1 + 1 ];
  2923. const z1 = src1[ srcOffset1 + 2 ];
  2924. const w1 = src1[ srcOffset1 + 3 ];
  2925. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2926. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2927. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2928. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2929. return dst;
  2930. }
  2931. /**
  2932. * The x value of this quaternion.
  2933. *
  2934. * @type {number}
  2935. * @default 0
  2936. */
  2937. get x() {
  2938. return this._x;
  2939. }
  2940. set x( value ) {
  2941. this._x = value;
  2942. this._onChangeCallback();
  2943. }
  2944. /**
  2945. * The y value of this quaternion.
  2946. *
  2947. * @type {number}
  2948. * @default 0
  2949. */
  2950. get y() {
  2951. return this._y;
  2952. }
  2953. set y( value ) {
  2954. this._y = value;
  2955. this._onChangeCallback();
  2956. }
  2957. /**
  2958. * The z value of this quaternion.
  2959. *
  2960. * @type {number}
  2961. * @default 0
  2962. */
  2963. get z() {
  2964. return this._z;
  2965. }
  2966. set z( value ) {
  2967. this._z = value;
  2968. this._onChangeCallback();
  2969. }
  2970. /**
  2971. * The w value of this quaternion.
  2972. *
  2973. * @type {number}
  2974. * @default 1
  2975. */
  2976. get w() {
  2977. return this._w;
  2978. }
  2979. set w( value ) {
  2980. this._w = value;
  2981. this._onChangeCallback();
  2982. }
  2983. /**
  2984. * Sets the quaternion components.
  2985. *
  2986. * @param {number} x - The x value of this quaternion.
  2987. * @param {number} y - The y value of this quaternion.
  2988. * @param {number} z - The z value of this quaternion.
  2989. * @param {number} w - The w value of this quaternion.
  2990. * @return {Quaternion} A reference to this quaternion.
  2991. */
  2992. set( x, y, z, w ) {
  2993. this._x = x;
  2994. this._y = y;
  2995. this._z = z;
  2996. this._w = w;
  2997. this._onChangeCallback();
  2998. return this;
  2999. }
  3000. /**
  3001. * Returns a new quaternion with copied values from this instance.
  3002. *
  3003. * @return {Quaternion} A clone of this instance.
  3004. */
  3005. clone() {
  3006. return new this.constructor( this._x, this._y, this._z, this._w );
  3007. }
  3008. /**
  3009. * Copies the values of the given quaternion to this instance.
  3010. *
  3011. * @param {Quaternion} quaternion - The quaternion to copy.
  3012. * @return {Quaternion} A reference to this quaternion.
  3013. */
  3014. copy( quaternion ) {
  3015. this._x = quaternion.x;
  3016. this._y = quaternion.y;
  3017. this._z = quaternion.z;
  3018. this._w = quaternion.w;
  3019. this._onChangeCallback();
  3020. return this;
  3021. }
  3022. /**
  3023. * Sets this quaternion from the rotation specified by the given
  3024. * Euler angles.
  3025. *
  3026. * @param {Euler} euler - The Euler angles.
  3027. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3028. * @return {Quaternion} A reference to this quaternion.
  3029. */
  3030. setFromEuler( euler, update = true ) {
  3031. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3032. // http://www.mathworks.com/matlabcentral/fileexchange/
  3033. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3034. // content/SpinCalc.m
  3035. const cos = Math.cos;
  3036. const sin = Math.sin;
  3037. const c1 = cos( x / 2 );
  3038. const c2 = cos( y / 2 );
  3039. const c3 = cos( z / 2 );
  3040. const s1 = sin( x / 2 );
  3041. const s2 = sin( y / 2 );
  3042. const s3 = sin( z / 2 );
  3043. switch ( order ) {
  3044. case 'XYZ':
  3045. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3046. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3047. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3048. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3049. break;
  3050. case 'YXZ':
  3051. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3052. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3053. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3054. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3055. break;
  3056. case 'ZXY':
  3057. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3058. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3059. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3060. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3061. break;
  3062. case 'ZYX':
  3063. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3064. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3065. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3066. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3067. break;
  3068. case 'YZX':
  3069. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3070. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3071. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3072. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3073. break;
  3074. case 'XZY':
  3075. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3076. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3077. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3078. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3079. break;
  3080. default:
  3081. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3082. }
  3083. if ( update === true ) this._onChangeCallback();
  3084. return this;
  3085. }
  3086. /**
  3087. * Sets this quaternion from the given axis and angle.
  3088. *
  3089. * @param {Vector3} axis - The normalized axis.
  3090. * @param {number} angle - The angle in radians.
  3091. * @return {Quaternion} A reference to this quaternion.
  3092. */
  3093. setFromAxisAngle( axis, angle ) {
  3094. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3095. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3096. this._x = axis.x * s;
  3097. this._y = axis.y * s;
  3098. this._z = axis.z * s;
  3099. this._w = Math.cos( halfAngle );
  3100. this._onChangeCallback();
  3101. return this;
  3102. }
  3103. /**
  3104. * Sets this quaternion from the given rotation matrix.
  3105. *
  3106. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3107. * @return {Quaternion} A reference to this quaternion.
  3108. */
  3109. setFromRotationMatrix( m ) {
  3110. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3111. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3112. const te = m.elements,
  3113. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3114. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3115. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3116. trace = m11 + m22 + m33;
  3117. if ( trace > 0 ) {
  3118. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3119. this._w = 0.25 / s;
  3120. this._x = ( m32 - m23 ) * s;
  3121. this._y = ( m13 - m31 ) * s;
  3122. this._z = ( m21 - m12 ) * s;
  3123. } else if ( m11 > m22 && m11 > m33 ) {
  3124. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3125. this._w = ( m32 - m23 ) / s;
  3126. this._x = 0.25 * s;
  3127. this._y = ( m12 + m21 ) / s;
  3128. this._z = ( m13 + m31 ) / s;
  3129. } else if ( m22 > m33 ) {
  3130. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3131. this._w = ( m13 - m31 ) / s;
  3132. this._x = ( m12 + m21 ) / s;
  3133. this._y = 0.25 * s;
  3134. this._z = ( m23 + m32 ) / s;
  3135. } else {
  3136. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3137. this._w = ( m21 - m12 ) / s;
  3138. this._x = ( m13 + m31 ) / s;
  3139. this._y = ( m23 + m32 ) / s;
  3140. this._z = 0.25 * s;
  3141. }
  3142. this._onChangeCallback();
  3143. return this;
  3144. }
  3145. /**
  3146. * Sets this quaternion to the rotation required to rotate the direction vector
  3147. * `vFrom` to the direction vector `vTo`.
  3148. *
  3149. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3150. * @param {Vector3} vTo - The second (normalized) direction vector.
  3151. * @return {Quaternion} A reference to this quaternion.
  3152. */
  3153. setFromUnitVectors( vFrom, vTo ) {
  3154. // assumes direction vectors vFrom and vTo are normalized
  3155. let r = vFrom.dot( vTo ) + 1;
  3156. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3157. // vFrom and vTo point in opposite directions
  3158. r = 0;
  3159. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3160. this._x = - vFrom.y;
  3161. this._y = vFrom.x;
  3162. this._z = 0;
  3163. this._w = r;
  3164. } else {
  3165. this._x = 0;
  3166. this._y = - vFrom.z;
  3167. this._z = vFrom.y;
  3168. this._w = r;
  3169. }
  3170. } else {
  3171. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3172. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3173. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3174. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3175. this._w = r;
  3176. }
  3177. return this.normalize();
  3178. }
  3179. /**
  3180. * Returns the angle between this quaternion and the given one in radians.
  3181. *
  3182. * @param {Quaternion} q - The quaternion to compute the angle with.
  3183. * @return {number} The angle in radians.
  3184. */
  3185. angleTo( q ) {
  3186. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3187. }
  3188. /**
  3189. * Rotates this quaternion by a given angular step to the given quaternion.
  3190. * The method ensures that the final quaternion will not overshoot `q`.
  3191. *
  3192. * @param {Quaternion} q - The target quaternion.
  3193. * @param {number} step - The angular step in radians.
  3194. * @return {Quaternion} A reference to this quaternion.
  3195. */
  3196. rotateTowards( q, step ) {
  3197. const angle = this.angleTo( q );
  3198. if ( angle === 0 ) return this;
  3199. const t = Math.min( 1, step / angle );
  3200. this.slerp( q, t );
  3201. return this;
  3202. }
  3203. /**
  3204. * Sets this quaternion to the identity quaternion; that is, to the
  3205. * quaternion that represents "no rotation".
  3206. *
  3207. * @return {Quaternion} A reference to this quaternion.
  3208. */
  3209. identity() {
  3210. return this.set( 0, 0, 0, 1 );
  3211. }
  3212. /**
  3213. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3214. * quaternion is assumed to have unit length.
  3215. *
  3216. * @return {Quaternion} A reference to this quaternion.
  3217. */
  3218. invert() {
  3219. return this.conjugate();
  3220. }
  3221. /**
  3222. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3223. * quaternion represents the same rotation in the opposite direction about
  3224. * the rotational axis.
  3225. *
  3226. * @return {Quaternion} A reference to this quaternion.
  3227. */
  3228. conjugate() {
  3229. this._x *= -1;
  3230. this._y *= -1;
  3231. this._z *= -1;
  3232. this._onChangeCallback();
  3233. return this;
  3234. }
  3235. /**
  3236. * Calculates the dot product of this quaternion and the given one.
  3237. *
  3238. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3239. * @return {number} The result of the dot product.
  3240. */
  3241. dot( v ) {
  3242. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3243. }
  3244. /**
  3245. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3246. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3247. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3248. * {@link Quaternion#length}.
  3249. *
  3250. * @return {number} The squared Euclidean length.
  3251. */
  3252. lengthSq() {
  3253. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3254. }
  3255. /**
  3256. * Computes the Euclidean length (straight-line length) of this quaternion,
  3257. * considered as a 4 dimensional vector.
  3258. *
  3259. * @return {number} The Euclidean length.
  3260. */
  3261. length() {
  3262. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3263. }
  3264. /**
  3265. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3266. * the same rotation as this one, but has a length equal to `1`.
  3267. *
  3268. * @return {Quaternion} A reference to this quaternion.
  3269. */
  3270. normalize() {
  3271. let l = this.length();
  3272. if ( l === 0 ) {
  3273. this._x = 0;
  3274. this._y = 0;
  3275. this._z = 0;
  3276. this._w = 1;
  3277. } else {
  3278. l = 1 / l;
  3279. this._x = this._x * l;
  3280. this._y = this._y * l;
  3281. this._z = this._z * l;
  3282. this._w = this._w * l;
  3283. }
  3284. this._onChangeCallback();
  3285. return this;
  3286. }
  3287. /**
  3288. * Multiplies this quaternion by the given one.
  3289. *
  3290. * @param {Quaternion} q - The quaternion.
  3291. * @return {Quaternion} A reference to this quaternion.
  3292. */
  3293. multiply( q ) {
  3294. return this.multiplyQuaternions( this, q );
  3295. }
  3296. /**
  3297. * Pre-multiplies this quaternion by the given one.
  3298. *
  3299. * @param {Quaternion} q - The quaternion.
  3300. * @return {Quaternion} A reference to this quaternion.
  3301. */
  3302. premultiply( q ) {
  3303. return this.multiplyQuaternions( q, this );
  3304. }
  3305. /**
  3306. * Multiplies the given quaternions and stores the result in this instance.
  3307. *
  3308. * @param {Quaternion} a - The first quaternion.
  3309. * @param {Quaternion} b - The second quaternion.
  3310. * @return {Quaternion} A reference to this quaternion.
  3311. */
  3312. multiplyQuaternions( a, b ) {
  3313. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3314. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3315. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3316. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3317. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3318. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3319. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3320. this._onChangeCallback();
  3321. return this;
  3322. }
  3323. /**
  3324. * Performs a spherical linear interpolation between quaternions.
  3325. *
  3326. * @param {Quaternion} qb - The target quaternion.
  3327. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3328. * @return {Quaternion} A reference to this quaternion.
  3329. */
  3330. slerp( qb, t ) {
  3331. if ( t === 0 ) return this;
  3332. if ( t === 1 ) return this.copy( qb );
  3333. const x = this._x, y = this._y, z = this._z, w = this._w;
  3334. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3335. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  3336. if ( cosHalfTheta < 0 ) {
  3337. this._w = - qb._w;
  3338. this._x = - qb._x;
  3339. this._y = - qb._y;
  3340. this._z = - qb._z;
  3341. cosHalfTheta = - cosHalfTheta;
  3342. } else {
  3343. this.copy( qb );
  3344. }
  3345. if ( cosHalfTheta >= 1.0 ) {
  3346. this._w = w;
  3347. this._x = x;
  3348. this._y = y;
  3349. this._z = z;
  3350. return this;
  3351. }
  3352. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  3353. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  3354. const s = 1 - t;
  3355. this._w = s * w + t * this._w;
  3356. this._x = s * x + t * this._x;
  3357. this._y = s * y + t * this._y;
  3358. this._z = s * z + t * this._z;
  3359. this.normalize(); // normalize calls _onChangeCallback()
  3360. return this;
  3361. }
  3362. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  3363. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  3364. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3365. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3366. this._w = ( w * ratioA + this._w * ratioB );
  3367. this._x = ( x * ratioA + this._x * ratioB );
  3368. this._y = ( y * ratioA + this._y * ratioB );
  3369. this._z = ( z * ratioA + this._z * ratioB );
  3370. this._onChangeCallback();
  3371. return this;
  3372. }
  3373. /**
  3374. * Performs a spherical linear interpolation between the given quaternions
  3375. * and stores the result in this quaternion.
  3376. *
  3377. * @param {Quaternion} qa - The source quaternion.
  3378. * @param {Quaternion} qb - The target quaternion.
  3379. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3380. * @return {Quaternion} A reference to this quaternion.
  3381. */
  3382. slerpQuaternions( qa, qb, t ) {
  3383. return this.copy( qa ).slerp( qb, t );
  3384. }
  3385. /**
  3386. * Sets this quaternion to a uniformly random, normalized quaternion.
  3387. *
  3388. * @return {Quaternion} A reference to this quaternion.
  3389. */
  3390. random() {
  3391. // Ken Shoemake
  3392. // Uniform random rotations
  3393. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3394. const theta1 = 2 * Math.PI * Math.random();
  3395. const theta2 = 2 * Math.PI * Math.random();
  3396. const x0 = Math.random();
  3397. const r1 = Math.sqrt( 1 - x0 );
  3398. const r2 = Math.sqrt( x0 );
  3399. return this.set(
  3400. r1 * Math.sin( theta1 ),
  3401. r1 * Math.cos( theta1 ),
  3402. r2 * Math.sin( theta2 ),
  3403. r2 * Math.cos( theta2 ),
  3404. );
  3405. }
  3406. /**
  3407. * Returns `true` if this quaternion is equal with the given one.
  3408. *
  3409. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3410. * @return {boolean} Whether this quaternion is equal with the given one.
  3411. */
  3412. equals( quaternion ) {
  3413. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3414. }
  3415. /**
  3416. * Sets this quaternion's components from the given array.
  3417. *
  3418. * @param {Array<number>} array - An array holding the quaternion component values.
  3419. * @param {number} [offset=0] - The offset into the array.
  3420. * @return {Quaternion} A reference to this quaternion.
  3421. */
  3422. fromArray( array, offset = 0 ) {
  3423. this._x = array[ offset ];
  3424. this._y = array[ offset + 1 ];
  3425. this._z = array[ offset + 2 ];
  3426. this._w = array[ offset + 3 ];
  3427. this._onChangeCallback();
  3428. return this;
  3429. }
  3430. /**
  3431. * Writes the components of this quaternion to the given array. If no array is provided,
  3432. * the method returns a new instance.
  3433. *
  3434. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3435. * @param {number} [offset=0] - Index of the first element in the array.
  3436. * @return {Array<number>} The quaternion components.
  3437. */
  3438. toArray( array = [], offset = 0 ) {
  3439. array[ offset ] = this._x;
  3440. array[ offset + 1 ] = this._y;
  3441. array[ offset + 2 ] = this._z;
  3442. array[ offset + 3 ] = this._w;
  3443. return array;
  3444. }
  3445. /**
  3446. * Sets the components of this quaternion from the given buffer attribute.
  3447. *
  3448. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3449. * @param {number} index - The index into the attribute.
  3450. * @return {Quaternion} A reference to this quaternion.
  3451. */
  3452. fromBufferAttribute( attribute, index ) {
  3453. this._x = attribute.getX( index );
  3454. this._y = attribute.getY( index );
  3455. this._z = attribute.getZ( index );
  3456. this._w = attribute.getW( index );
  3457. this._onChangeCallback();
  3458. return this;
  3459. }
  3460. /**
  3461. * This methods defines the serialization result of this class. Returns the
  3462. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3463. *
  3464. * @return {Array<number>} The serialized quaternion.
  3465. */
  3466. toJSON() {
  3467. return this.toArray();
  3468. }
  3469. _onChange( callback ) {
  3470. this._onChangeCallback = callback;
  3471. return this;
  3472. }
  3473. _onChangeCallback() {}
  3474. *[ Symbol.iterator ]() {
  3475. yield this._x;
  3476. yield this._y;
  3477. yield this._z;
  3478. yield this._w;
  3479. }
  3480. }
  3481. /**
  3482. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3483. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3484. *
  3485. * - A point in 3D space.
  3486. * - A direction and length in 3D space. In three.js the length will
  3487. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3488. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3489. * - Any arbitrary ordered triplet of numbers.
  3490. *
  3491. * There are other things a 3D vector can be used to represent, such as
  3492. * momentum vectors and so on, however these are the most
  3493. * common uses in three.js.
  3494. *
  3495. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3496. * the corresponding order.
  3497. * ```js
  3498. * const a = new THREE.Vector3( 0, 1, 0 );
  3499. *
  3500. * //no arguments; will be initialised to (0, 0, 0)
  3501. * const b = new THREE.Vector3( );
  3502. *
  3503. * const d = a.distanceTo( b );
  3504. * ```
  3505. */
  3506. class Vector3 {
  3507. /**
  3508. * Constructs a new 3D vector.
  3509. *
  3510. * @param {number} [x=0] - The x value of this vector.
  3511. * @param {number} [y=0] - The y value of this vector.
  3512. * @param {number} [z=0] - The z value of this vector.
  3513. */
  3514. constructor( x = 0, y = 0, z = 0 ) {
  3515. /**
  3516. * This flag can be used for type testing.
  3517. *
  3518. * @type {boolean}
  3519. * @readonly
  3520. * @default true
  3521. */
  3522. Vector3.prototype.isVector3 = true;
  3523. /**
  3524. * The x value of this vector.
  3525. *
  3526. * @type {number}
  3527. */
  3528. this.x = x;
  3529. /**
  3530. * The y value of this vector.
  3531. *
  3532. * @type {number}
  3533. */
  3534. this.y = y;
  3535. /**
  3536. * The z value of this vector.
  3537. *
  3538. * @type {number}
  3539. */
  3540. this.z = z;
  3541. }
  3542. /**
  3543. * Sets the vector components.
  3544. *
  3545. * @param {number} x - The value of the x component.
  3546. * @param {number} y - The value of the y component.
  3547. * @param {number} z - The value of the z component.
  3548. * @return {Vector3} A reference to this vector.
  3549. */
  3550. set( x, y, z ) {
  3551. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3552. this.x = x;
  3553. this.y = y;
  3554. this.z = z;
  3555. return this;
  3556. }
  3557. /**
  3558. * Sets the vector components to the same value.
  3559. *
  3560. * @param {number} scalar - The value to set for all vector components.
  3561. * @return {Vector3} A reference to this vector.
  3562. */
  3563. setScalar( scalar ) {
  3564. this.x = scalar;
  3565. this.y = scalar;
  3566. this.z = scalar;
  3567. return this;
  3568. }
  3569. /**
  3570. * Sets the vector's x component to the given value
  3571. *
  3572. * @param {number} x - The value to set.
  3573. * @return {Vector3} A reference to this vector.
  3574. */
  3575. setX( x ) {
  3576. this.x = x;
  3577. return this;
  3578. }
  3579. /**
  3580. * Sets the vector's y component to the given value
  3581. *
  3582. * @param {number} y - The value to set.
  3583. * @return {Vector3} A reference to this vector.
  3584. */
  3585. setY( y ) {
  3586. this.y = y;
  3587. return this;
  3588. }
  3589. /**
  3590. * Sets the vector's z component to the given value
  3591. *
  3592. * @param {number} z - The value to set.
  3593. * @return {Vector3} A reference to this vector.
  3594. */
  3595. setZ( z ) {
  3596. this.z = z;
  3597. return this;
  3598. }
  3599. /**
  3600. * Allows to set a vector component with an index.
  3601. *
  3602. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3603. * @param {number} value - The value to set.
  3604. * @return {Vector3} A reference to this vector.
  3605. */
  3606. setComponent( index, value ) {
  3607. switch ( index ) {
  3608. case 0: this.x = value; break;
  3609. case 1: this.y = value; break;
  3610. case 2: this.z = value; break;
  3611. default: throw new Error( 'index is out of range: ' + index );
  3612. }
  3613. return this;
  3614. }
  3615. /**
  3616. * Returns the value of the vector component which matches the given index.
  3617. *
  3618. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3619. * @return {number} A vector component value.
  3620. */
  3621. getComponent( index ) {
  3622. switch ( index ) {
  3623. case 0: return this.x;
  3624. case 1: return this.y;
  3625. case 2: return this.z;
  3626. default: throw new Error( 'index is out of range: ' + index );
  3627. }
  3628. }
  3629. /**
  3630. * Returns a new vector with copied values from this instance.
  3631. *
  3632. * @return {Vector3} A clone of this instance.
  3633. */
  3634. clone() {
  3635. return new this.constructor( this.x, this.y, this.z );
  3636. }
  3637. /**
  3638. * Copies the values of the given vector to this instance.
  3639. *
  3640. * @param {Vector3} v - The vector to copy.
  3641. * @return {Vector3} A reference to this vector.
  3642. */
  3643. copy( v ) {
  3644. this.x = v.x;
  3645. this.y = v.y;
  3646. this.z = v.z;
  3647. return this;
  3648. }
  3649. /**
  3650. * Adds the given vector to this instance.
  3651. *
  3652. * @param {Vector3} v - The vector to add.
  3653. * @return {Vector3} A reference to this vector.
  3654. */
  3655. add( v ) {
  3656. this.x += v.x;
  3657. this.y += v.y;
  3658. this.z += v.z;
  3659. return this;
  3660. }
  3661. /**
  3662. * Adds the given scalar value to all components of this instance.
  3663. *
  3664. * @param {number} s - The scalar to add.
  3665. * @return {Vector3} A reference to this vector.
  3666. */
  3667. addScalar( s ) {
  3668. this.x += s;
  3669. this.y += s;
  3670. this.z += s;
  3671. return this;
  3672. }
  3673. /**
  3674. * Adds the given vectors and stores the result in this instance.
  3675. *
  3676. * @param {Vector3} a - The first vector.
  3677. * @param {Vector3} b - The second vector.
  3678. * @return {Vector3} A reference to this vector.
  3679. */
  3680. addVectors( a, b ) {
  3681. this.x = a.x + b.x;
  3682. this.y = a.y + b.y;
  3683. this.z = a.z + b.z;
  3684. return this;
  3685. }
  3686. /**
  3687. * Adds the given vector scaled by the given factor to this instance.
  3688. *
  3689. * @param {Vector3|Vector4} v - The vector.
  3690. * @param {number} s - The factor that scales `v`.
  3691. * @return {Vector3} A reference to this vector.
  3692. */
  3693. addScaledVector( v, s ) {
  3694. this.x += v.x * s;
  3695. this.y += v.y * s;
  3696. this.z += v.z * s;
  3697. return this;
  3698. }
  3699. /**
  3700. * Subtracts the given vector from this instance.
  3701. *
  3702. * @param {Vector3} v - The vector to subtract.
  3703. * @return {Vector3} A reference to this vector.
  3704. */
  3705. sub( v ) {
  3706. this.x -= v.x;
  3707. this.y -= v.y;
  3708. this.z -= v.z;
  3709. return this;
  3710. }
  3711. /**
  3712. * Subtracts the given scalar value from all components of this instance.
  3713. *
  3714. * @param {number} s - The scalar to subtract.
  3715. * @return {Vector3} A reference to this vector.
  3716. */
  3717. subScalar( s ) {
  3718. this.x -= s;
  3719. this.y -= s;
  3720. this.z -= s;
  3721. return this;
  3722. }
  3723. /**
  3724. * Subtracts the given vectors and stores the result in this instance.
  3725. *
  3726. * @param {Vector3} a - The first vector.
  3727. * @param {Vector3} b - The second vector.
  3728. * @return {Vector3} A reference to this vector.
  3729. */
  3730. subVectors( a, b ) {
  3731. this.x = a.x - b.x;
  3732. this.y = a.y - b.y;
  3733. this.z = a.z - b.z;
  3734. return this;
  3735. }
  3736. /**
  3737. * Multiplies the given vector with this instance.
  3738. *
  3739. * @param {Vector3} v - The vector to multiply.
  3740. * @return {Vector3} A reference to this vector.
  3741. */
  3742. multiply( v ) {
  3743. this.x *= v.x;
  3744. this.y *= v.y;
  3745. this.z *= v.z;
  3746. return this;
  3747. }
  3748. /**
  3749. * Multiplies the given scalar value with all components of this instance.
  3750. *
  3751. * @param {number} scalar - The scalar to multiply.
  3752. * @return {Vector3} A reference to this vector.
  3753. */
  3754. multiplyScalar( scalar ) {
  3755. this.x *= scalar;
  3756. this.y *= scalar;
  3757. this.z *= scalar;
  3758. return this;
  3759. }
  3760. /**
  3761. * Multiplies the given vectors and stores the result in this instance.
  3762. *
  3763. * @param {Vector3} a - The first vector.
  3764. * @param {Vector3} b - The second vector.
  3765. * @return {Vector3} A reference to this vector.
  3766. */
  3767. multiplyVectors( a, b ) {
  3768. this.x = a.x * b.x;
  3769. this.y = a.y * b.y;
  3770. this.z = a.z * b.z;
  3771. return this;
  3772. }
  3773. /**
  3774. * Applies the given Euler rotation to this vector.
  3775. *
  3776. * @param {Euler} euler - The Euler angles.
  3777. * @return {Vector3} A reference to this vector.
  3778. */
  3779. applyEuler( euler ) {
  3780. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3781. }
  3782. /**
  3783. * Applies a rotation specified by an axis and an angle to this vector.
  3784. *
  3785. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3786. * @param {number} angle - The angle in radians.
  3787. * @return {Vector3} A reference to this vector.
  3788. */
  3789. applyAxisAngle( axis, angle ) {
  3790. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3791. }
  3792. /**
  3793. * Multiplies this vector with the given 3x3 matrix.
  3794. *
  3795. * @param {Matrix3} m - The 3x3 matrix.
  3796. * @return {Vector3} A reference to this vector.
  3797. */
  3798. applyMatrix3( m ) {
  3799. const x = this.x, y = this.y, z = this.z;
  3800. const e = m.elements;
  3801. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3802. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3803. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3804. return this;
  3805. }
  3806. /**
  3807. * Multiplies this vector by the given normal matrix and normalizes
  3808. * the result.
  3809. *
  3810. * @param {Matrix3} m - The normal matrix.
  3811. * @return {Vector3} A reference to this vector.
  3812. */
  3813. applyNormalMatrix( m ) {
  3814. return this.applyMatrix3( m ).normalize();
  3815. }
  3816. /**
  3817. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3818. * divides by perspective.
  3819. *
  3820. * @param {Matrix4} m - The matrix to apply.
  3821. * @return {Vector3} A reference to this vector.
  3822. */
  3823. applyMatrix4( m ) {
  3824. const x = this.x, y = this.y, z = this.z;
  3825. const e = m.elements;
  3826. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3827. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3828. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3829. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3830. return this;
  3831. }
  3832. /**
  3833. * Applies the given Quaternion to this vector.
  3834. *
  3835. * @param {Quaternion} q - The Quaternion.
  3836. * @return {Vector3} A reference to this vector.
  3837. */
  3838. applyQuaternion( q ) {
  3839. // quaternion q is assumed to have unit length
  3840. const vx = this.x, vy = this.y, vz = this.z;
  3841. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3842. // t = 2 * cross( q.xyz, v );
  3843. const tx = 2 * ( qy * vz - qz * vy );
  3844. const ty = 2 * ( qz * vx - qx * vz );
  3845. const tz = 2 * ( qx * vy - qy * vx );
  3846. // v + q.w * t + cross( q.xyz, t );
  3847. this.x = vx + qw * tx + qy * tz - qz * ty;
  3848. this.y = vy + qw * ty + qz * tx - qx * tz;
  3849. this.z = vz + qw * tz + qx * ty - qy * tx;
  3850. return this;
  3851. }
  3852. /**
  3853. * Projects this vector from world space into the camera's normalized
  3854. * device coordinate (NDC) space.
  3855. *
  3856. * @param {Camera} camera - The camera.
  3857. * @return {Vector3} A reference to this vector.
  3858. */
  3859. project( camera ) {
  3860. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3861. }
  3862. /**
  3863. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  3864. * space into world space.
  3865. *
  3866. * @param {Camera} camera - The camera.
  3867. * @return {Vector3} A reference to this vector.
  3868. */
  3869. unproject( camera ) {
  3870. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  3871. }
  3872. /**
  3873. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  3874. * subset of the given 4x4 matrix and then normalizes the result.
  3875. *
  3876. * @param {Matrix4} m - The matrix.
  3877. * @return {Vector3} A reference to this vector.
  3878. */
  3879. transformDirection( m ) {
  3880. // input: THREE.Matrix4 affine matrix
  3881. // vector interpreted as a direction
  3882. const x = this.x, y = this.y, z = this.z;
  3883. const e = m.elements;
  3884. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  3885. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  3886. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  3887. return this.normalize();
  3888. }
  3889. /**
  3890. * Divides this instance by the given vector.
  3891. *
  3892. * @param {Vector3} v - The vector to divide.
  3893. * @return {Vector3} A reference to this vector.
  3894. */
  3895. divide( v ) {
  3896. this.x /= v.x;
  3897. this.y /= v.y;
  3898. this.z /= v.z;
  3899. return this;
  3900. }
  3901. /**
  3902. * Divides this vector by the given scalar.
  3903. *
  3904. * @param {number} scalar - The scalar to divide.
  3905. * @return {Vector3} A reference to this vector.
  3906. */
  3907. divideScalar( scalar ) {
  3908. return this.multiplyScalar( 1 / scalar );
  3909. }
  3910. /**
  3911. * If this vector's x, y or z value is greater than the given vector's x, y or z
  3912. * value, replace that value with the corresponding min value.
  3913. *
  3914. * @param {Vector3} v - The vector.
  3915. * @return {Vector3} A reference to this vector.
  3916. */
  3917. min( v ) {
  3918. this.x = Math.min( this.x, v.x );
  3919. this.y = Math.min( this.y, v.y );
  3920. this.z = Math.min( this.z, v.z );
  3921. return this;
  3922. }
  3923. /**
  3924. * If this vector's x, y or z value is less than the given vector's x, y or z
  3925. * value, replace that value with the corresponding max value.
  3926. *
  3927. * @param {Vector3} v - The vector.
  3928. * @return {Vector3} A reference to this vector.
  3929. */
  3930. max( v ) {
  3931. this.x = Math.max( this.x, v.x );
  3932. this.y = Math.max( this.y, v.y );
  3933. this.z = Math.max( this.z, v.z );
  3934. return this;
  3935. }
  3936. /**
  3937. * If this vector's x, y or z value is greater than the max vector's x, y or z
  3938. * value, it is replaced by the corresponding value.
  3939. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  3940. * it is replaced by the corresponding value.
  3941. *
  3942. * @param {Vector3} min - The minimum x, y and z values.
  3943. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  3944. * @return {Vector3} A reference to this vector.
  3945. */
  3946. clamp( min, max ) {
  3947. // assumes min < max, componentwise
  3948. this.x = clamp( this.x, min.x, max.x );
  3949. this.y = clamp( this.y, min.y, max.y );
  3950. this.z = clamp( this.z, min.z, max.z );
  3951. return this;
  3952. }
  3953. /**
  3954. * If this vector's x, y or z values are greater than the max value, they are
  3955. * replaced by the max value.
  3956. * If this vector's x, y or z values are less than the min value, they are
  3957. * replaced by the min value.
  3958. *
  3959. * @param {number} minVal - The minimum value the components will be clamped to.
  3960. * @param {number} maxVal - The maximum value the components will be clamped to.
  3961. * @return {Vector3} A reference to this vector.
  3962. */
  3963. clampScalar( minVal, maxVal ) {
  3964. this.x = clamp( this.x, minVal, maxVal );
  3965. this.y = clamp( this.y, minVal, maxVal );
  3966. this.z = clamp( this.z, minVal, maxVal );
  3967. return this;
  3968. }
  3969. /**
  3970. * If this vector's length is greater than the max value, it is replaced by
  3971. * the max value.
  3972. * If this vector's length is less than the min value, it is replaced by the
  3973. * min value.
  3974. *
  3975. * @param {number} min - The minimum value the vector length will be clamped to.
  3976. * @param {number} max - The maximum value the vector length will be clamped to.
  3977. * @return {Vector3} A reference to this vector.
  3978. */
  3979. clampLength( min, max ) {
  3980. const length = this.length();
  3981. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3982. }
  3983. /**
  3984. * The components of this vector are rounded down to the nearest integer value.
  3985. *
  3986. * @return {Vector3} A reference to this vector.
  3987. */
  3988. floor() {
  3989. this.x = Math.floor( this.x );
  3990. this.y = Math.floor( this.y );
  3991. this.z = Math.floor( this.z );
  3992. return this;
  3993. }
  3994. /**
  3995. * The components of this vector are rounded up to the nearest integer value.
  3996. *
  3997. * @return {Vector3} A reference to this vector.
  3998. */
  3999. ceil() {
  4000. this.x = Math.ceil( this.x );
  4001. this.y = Math.ceil( this.y );
  4002. this.z = Math.ceil( this.z );
  4003. return this;
  4004. }
  4005. /**
  4006. * The components of this vector are rounded to the nearest integer value
  4007. *
  4008. * @return {Vector3} A reference to this vector.
  4009. */
  4010. round() {
  4011. this.x = Math.round( this.x );
  4012. this.y = Math.round( this.y );
  4013. this.z = Math.round( this.z );
  4014. return this;
  4015. }
  4016. /**
  4017. * The components of this vector are rounded towards zero (up if negative,
  4018. * down if positive) to an integer value.
  4019. *
  4020. * @return {Vector3} A reference to this vector.
  4021. */
  4022. roundToZero() {
  4023. this.x = Math.trunc( this.x );
  4024. this.y = Math.trunc( this.y );
  4025. this.z = Math.trunc( this.z );
  4026. return this;
  4027. }
  4028. /**
  4029. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4030. *
  4031. * @return {Vector3} A reference to this vector.
  4032. */
  4033. negate() {
  4034. this.x = - this.x;
  4035. this.y = - this.y;
  4036. this.z = - this.z;
  4037. return this;
  4038. }
  4039. /**
  4040. * Calculates the dot product of the given vector with this instance.
  4041. *
  4042. * @param {Vector3} v - The vector to compute the dot product with.
  4043. * @return {number} The result of the dot product.
  4044. */
  4045. dot( v ) {
  4046. return this.x * v.x + this.y * v.y + this.z * v.z;
  4047. }
  4048. // TODO lengthSquared?
  4049. /**
  4050. * Computes the square of the Euclidean length (straight-line length) from
  4051. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4052. * compare the length squared instead as it is slightly more efficient to calculate.
  4053. *
  4054. * @return {number} The square length of this vector.
  4055. */
  4056. lengthSq() {
  4057. return this.x * this.x + this.y * this.y + this.z * this.z;
  4058. }
  4059. /**
  4060. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4061. *
  4062. * @return {number} The length of this vector.
  4063. */
  4064. length() {
  4065. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4066. }
  4067. /**
  4068. * Computes the Manhattan length of this vector.
  4069. *
  4070. * @return {number} The length of this vector.
  4071. */
  4072. manhattanLength() {
  4073. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4074. }
  4075. /**
  4076. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4077. * with the same direction as this one, but with a vector length of `1`.
  4078. *
  4079. * @return {Vector3} A reference to this vector.
  4080. */
  4081. normalize() {
  4082. return this.divideScalar( this.length() || 1 );
  4083. }
  4084. /**
  4085. * Sets this vector to a vector with the same direction as this one, but
  4086. * with the specified length.
  4087. *
  4088. * @param {number} length - The new length of this vector.
  4089. * @return {Vector3} A reference to this vector.
  4090. */
  4091. setLength( length ) {
  4092. return this.normalize().multiplyScalar( length );
  4093. }
  4094. /**
  4095. * Linearly interpolates between the given vector and this instance, where
  4096. * alpha is the percent distance along the line - alpha = 0 will be this
  4097. * vector, and alpha = 1 will be the given one.
  4098. *
  4099. * @param {Vector3} v - The vector to interpolate towards.
  4100. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4101. * @return {Vector3} A reference to this vector.
  4102. */
  4103. lerp( v, alpha ) {
  4104. this.x += ( v.x - this.x ) * alpha;
  4105. this.y += ( v.y - this.y ) * alpha;
  4106. this.z += ( v.z - this.z ) * alpha;
  4107. return this;
  4108. }
  4109. /**
  4110. * Linearly interpolates between the given vectors, where alpha is the percent
  4111. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4112. * be the second one. The result is stored in this instance.
  4113. *
  4114. * @param {Vector3} v1 - The first vector.
  4115. * @param {Vector3} v2 - The second vector.
  4116. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4117. * @return {Vector3} A reference to this vector.
  4118. */
  4119. lerpVectors( v1, v2, alpha ) {
  4120. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4121. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4122. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4123. return this;
  4124. }
  4125. /**
  4126. * Calculates the cross product of the given vector with this instance.
  4127. *
  4128. * @param {Vector3} v - The vector to compute the cross product with.
  4129. * @return {Vector3} The result of the cross product.
  4130. */
  4131. cross( v ) {
  4132. return this.crossVectors( this, v );
  4133. }
  4134. /**
  4135. * Calculates the cross product of the given vectors and stores the result
  4136. * in this instance.
  4137. *
  4138. * @param {Vector3} a - The first vector.
  4139. * @param {Vector3} b - The second vector.
  4140. * @return {Vector3} A reference to this vector.
  4141. */
  4142. crossVectors( a, b ) {
  4143. const ax = a.x, ay = a.y, az = a.z;
  4144. const bx = b.x, by = b.y, bz = b.z;
  4145. this.x = ay * bz - az * by;
  4146. this.y = az * bx - ax * bz;
  4147. this.z = ax * by - ay * bx;
  4148. return this;
  4149. }
  4150. /**
  4151. * Projects this vector onto the given one.
  4152. *
  4153. * @param {Vector3} v - The vector to project to.
  4154. * @return {Vector3} A reference to this vector.
  4155. */
  4156. projectOnVector( v ) {
  4157. const denominator = v.lengthSq();
  4158. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4159. const scalar = v.dot( this ) / denominator;
  4160. return this.copy( v ).multiplyScalar( scalar );
  4161. }
  4162. /**
  4163. * Projects this vector onto a plane by subtracting this
  4164. * vector projected onto the plane's normal from this vector.
  4165. *
  4166. * @param {Vector3} planeNormal - The plane normal.
  4167. * @return {Vector3} A reference to this vector.
  4168. */
  4169. projectOnPlane( planeNormal ) {
  4170. _vector$c.copy( this ).projectOnVector( planeNormal );
  4171. return this.sub( _vector$c );
  4172. }
  4173. /**
  4174. * Reflects this vector off a plane orthogonal to the given normal vector.
  4175. *
  4176. * @param {Vector3} normal - The (normalized) normal vector.
  4177. * @return {Vector3} A reference to this vector.
  4178. */
  4179. reflect( normal ) {
  4180. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4181. }
  4182. /**
  4183. * Returns the angle between the given vector and this instance in radians.
  4184. *
  4185. * @param {Vector3} v - The vector to compute the angle with.
  4186. * @return {number} The angle in radians.
  4187. */
  4188. angleTo( v ) {
  4189. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4190. if ( denominator === 0 ) return Math.PI / 2;
  4191. const theta = this.dot( v ) / denominator;
  4192. // clamp, to handle numerical problems
  4193. return Math.acos( clamp( theta, -1, 1 ) );
  4194. }
  4195. /**
  4196. * Computes the distance from the given vector to this instance.
  4197. *
  4198. * @param {Vector3} v - The vector to compute the distance to.
  4199. * @return {number} The distance.
  4200. */
  4201. distanceTo( v ) {
  4202. return Math.sqrt( this.distanceToSquared( v ) );
  4203. }
  4204. /**
  4205. * Computes the squared distance from the given vector to this instance.
  4206. * If you are just comparing the distance with another distance, you should compare
  4207. * the distance squared instead as it is slightly more efficient to calculate.
  4208. *
  4209. * @param {Vector3} v - The vector to compute the squared distance to.
  4210. * @return {number} The squared distance.
  4211. */
  4212. distanceToSquared( v ) {
  4213. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4214. return dx * dx + dy * dy + dz * dz;
  4215. }
  4216. /**
  4217. * Computes the Manhattan distance from the given vector to this instance.
  4218. *
  4219. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4220. * @return {number} The Manhattan distance.
  4221. */
  4222. manhattanDistanceTo( v ) {
  4223. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4224. }
  4225. /**
  4226. * Sets the vector components from the given spherical coordinates.
  4227. *
  4228. * @param {Spherical} s - The spherical coordinates.
  4229. * @return {Vector3} A reference to this vector.
  4230. */
  4231. setFromSpherical( s ) {
  4232. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4233. }
  4234. /**
  4235. * Sets the vector components from the given spherical coordinates.
  4236. *
  4237. * @param {number} radius - The radius.
  4238. * @param {number} phi - The phi angle in radians.
  4239. * @param {number} theta - The theta angle in radians.
  4240. * @return {Vector3} A reference to this vector.
  4241. */
  4242. setFromSphericalCoords( radius, phi, theta ) {
  4243. const sinPhiRadius = Math.sin( phi ) * radius;
  4244. this.x = sinPhiRadius * Math.sin( theta );
  4245. this.y = Math.cos( phi ) * radius;
  4246. this.z = sinPhiRadius * Math.cos( theta );
  4247. return this;
  4248. }
  4249. /**
  4250. * Sets the vector components from the given cylindrical coordinates.
  4251. *
  4252. * @param {Cylindrical} c - The cylindrical coordinates.
  4253. * @return {Vector3} A reference to this vector.
  4254. */
  4255. setFromCylindrical( c ) {
  4256. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4257. }
  4258. /**
  4259. * Sets the vector components from the given cylindrical coordinates.
  4260. *
  4261. * @param {number} radius - The radius.
  4262. * @param {number} theta - The theta angle in radians.
  4263. * @param {number} y - The y value.
  4264. * @return {Vector3} A reference to this vector.
  4265. */
  4266. setFromCylindricalCoords( radius, theta, y ) {
  4267. this.x = radius * Math.sin( theta );
  4268. this.y = y;
  4269. this.z = radius * Math.cos( theta );
  4270. return this;
  4271. }
  4272. /**
  4273. * Sets the vector components to the position elements of the
  4274. * given transformation matrix.
  4275. *
  4276. * @param {Matrix4} m - The 4x4 matrix.
  4277. * @return {Vector3} A reference to this vector.
  4278. */
  4279. setFromMatrixPosition( m ) {
  4280. const e = m.elements;
  4281. this.x = e[ 12 ];
  4282. this.y = e[ 13 ];
  4283. this.z = e[ 14 ];
  4284. return this;
  4285. }
  4286. /**
  4287. * Sets the vector components to the scale elements of the
  4288. * given transformation matrix.
  4289. *
  4290. * @param {Matrix4} m - The 4x4 matrix.
  4291. * @return {Vector3} A reference to this vector.
  4292. */
  4293. setFromMatrixScale( m ) {
  4294. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4295. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4296. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4297. this.x = sx;
  4298. this.y = sy;
  4299. this.z = sz;
  4300. return this;
  4301. }
  4302. /**
  4303. * Sets the vector components from the specified matrix column.
  4304. *
  4305. * @param {Matrix4} m - The 4x4 matrix.
  4306. * @param {number} index - The column index.
  4307. * @return {Vector3} A reference to this vector.
  4308. */
  4309. setFromMatrixColumn( m, index ) {
  4310. return this.fromArray( m.elements, index * 4 );
  4311. }
  4312. /**
  4313. * Sets the vector components from the specified matrix column.
  4314. *
  4315. * @param {Matrix3} m - The 3x3 matrix.
  4316. * @param {number} index - The column index.
  4317. * @return {Vector3} A reference to this vector.
  4318. */
  4319. setFromMatrix3Column( m, index ) {
  4320. return this.fromArray( m.elements, index * 3 );
  4321. }
  4322. /**
  4323. * Sets the vector components from the given Euler angles.
  4324. *
  4325. * @param {Euler} e - The Euler angles to set.
  4326. * @return {Vector3} A reference to this vector.
  4327. */
  4328. setFromEuler( e ) {
  4329. this.x = e._x;
  4330. this.y = e._y;
  4331. this.z = e._z;
  4332. return this;
  4333. }
  4334. /**
  4335. * Sets the vector components from the RGB components of the
  4336. * given color.
  4337. *
  4338. * @param {Color} c - The color to set.
  4339. * @return {Vector3} A reference to this vector.
  4340. */
  4341. setFromColor( c ) {
  4342. this.x = c.r;
  4343. this.y = c.g;
  4344. this.z = c.b;
  4345. return this;
  4346. }
  4347. /**
  4348. * Returns `true` if this vector is equal with the given one.
  4349. *
  4350. * @param {Vector3} v - The vector to test for equality.
  4351. * @return {boolean} Whether this vector is equal with the given one.
  4352. */
  4353. equals( v ) {
  4354. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4355. }
  4356. /**
  4357. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4358. * and z value to be `array[ offset + 2 ]`.
  4359. *
  4360. * @param {Array<number>} array - An array holding the vector component values.
  4361. * @param {number} [offset=0] - The offset into the array.
  4362. * @return {Vector3} A reference to this vector.
  4363. */
  4364. fromArray( array, offset = 0 ) {
  4365. this.x = array[ offset ];
  4366. this.y = array[ offset + 1 ];
  4367. this.z = array[ offset + 2 ];
  4368. return this;
  4369. }
  4370. /**
  4371. * Writes the components of this vector to the given array. If no array is provided,
  4372. * the method returns a new instance.
  4373. *
  4374. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4375. * @param {number} [offset=0] - Index of the first element in the array.
  4376. * @return {Array<number>} The vector components.
  4377. */
  4378. toArray( array = [], offset = 0 ) {
  4379. array[ offset ] = this.x;
  4380. array[ offset + 1 ] = this.y;
  4381. array[ offset + 2 ] = this.z;
  4382. return array;
  4383. }
  4384. /**
  4385. * Sets the components of this vector from the given buffer attribute.
  4386. *
  4387. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4388. * @param {number} index - The index into the attribute.
  4389. * @return {Vector3} A reference to this vector.
  4390. */
  4391. fromBufferAttribute( attribute, index ) {
  4392. this.x = attribute.getX( index );
  4393. this.y = attribute.getY( index );
  4394. this.z = attribute.getZ( index );
  4395. return this;
  4396. }
  4397. /**
  4398. * Sets each component of this vector to a pseudo-random value between `0` and
  4399. * `1`, excluding `1`.
  4400. *
  4401. * @return {Vector3} A reference to this vector.
  4402. */
  4403. random() {
  4404. this.x = Math.random();
  4405. this.y = Math.random();
  4406. this.z = Math.random();
  4407. return this;
  4408. }
  4409. /**
  4410. * Sets this vector to a uniformly random point on a unit sphere.
  4411. *
  4412. * @return {Vector3} A reference to this vector.
  4413. */
  4414. randomDirection() {
  4415. // https://mathworld.wolfram.com/SpherePointPicking.html
  4416. const theta = Math.random() * Math.PI * 2;
  4417. const u = Math.random() * 2 - 1;
  4418. const c = Math.sqrt( 1 - u * u );
  4419. this.x = c * Math.cos( theta );
  4420. this.y = u;
  4421. this.z = c * Math.sin( theta );
  4422. return this;
  4423. }
  4424. *[ Symbol.iterator ]() {
  4425. yield this.x;
  4426. yield this.y;
  4427. yield this.z;
  4428. }
  4429. }
  4430. const _vector$c = /*@__PURE__*/ new Vector3();
  4431. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4432. /**
  4433. * Represents a 3x3 matrix.
  4434. *
  4435. * A Note on Row-Major and Column-Major Ordering:
  4436. *
  4437. * The constructor and {@link Matrix3#set} method take arguments in
  4438. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  4439. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4440. * This means that calling:
  4441. * ```js
  4442. * const m = new THREE.Matrix();
  4443. * m.set( 11, 12, 13,
  4444. * 21, 22, 23,
  4445. * 31, 32, 33 );
  4446. * ```
  4447. * will result in the elements array containing:
  4448. * ```js
  4449. * m.elements = [ 11, 21, 31,
  4450. * 12, 22, 32,
  4451. * 13, 23, 33 ];
  4452. * ```
  4453. * and internally all calculations are performed using column-major ordering.
  4454. * However, as the actual ordering makes no difference mathematically and
  4455. * most people are used to thinking about matrices in row-major order, the
  4456. * three.js documentation shows matrices in row-major order. Just bear in
  4457. * mind that if you are reading the source code, you'll have to take the
  4458. * transpose of any matrices outlined here to make sense of the calculations.
  4459. */
  4460. class Matrix3 {
  4461. /**
  4462. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4463. * in row-major order. If no arguments are provided, the constructor
  4464. * initializes the matrix as an identity matrix.
  4465. *
  4466. * @param {number} [n11] - 1-1 matrix element.
  4467. * @param {number} [n12] - 1-2 matrix element.
  4468. * @param {number} [n13] - 1-3 matrix element.
  4469. * @param {number} [n21] - 2-1 matrix element.
  4470. * @param {number} [n22] - 2-2 matrix element.
  4471. * @param {number} [n23] - 2-3 matrix element.
  4472. * @param {number} [n31] - 3-1 matrix element.
  4473. * @param {number} [n32] - 3-2 matrix element.
  4474. * @param {number} [n33] - 3-3 matrix element.
  4475. */
  4476. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4477. /**
  4478. * This flag can be used for type testing.
  4479. *
  4480. * @type {boolean}
  4481. * @readonly
  4482. * @default true
  4483. */
  4484. Matrix3.prototype.isMatrix3 = true;
  4485. /**
  4486. * A column-major list of matrix values.
  4487. *
  4488. * @type {Array<number>}
  4489. */
  4490. this.elements = [
  4491. 1, 0, 0,
  4492. 0, 1, 0,
  4493. 0, 0, 1
  4494. ];
  4495. if ( n11 !== undefined ) {
  4496. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4497. }
  4498. }
  4499. /**
  4500. * Sets the elements of the matrix.The arguments are supposed to be
  4501. * in row-major order.
  4502. *
  4503. * @param {number} [n11] - 1-1 matrix element.
  4504. * @param {number} [n12] - 1-2 matrix element.
  4505. * @param {number} [n13] - 1-3 matrix element.
  4506. * @param {number} [n21] - 2-1 matrix element.
  4507. * @param {number} [n22] - 2-2 matrix element.
  4508. * @param {number} [n23] - 2-3 matrix element.
  4509. * @param {number} [n31] - 3-1 matrix element.
  4510. * @param {number} [n32] - 3-2 matrix element.
  4511. * @param {number} [n33] - 3-3 matrix element.
  4512. * @return {Matrix3} A reference to this matrix.
  4513. */
  4514. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4515. const te = this.elements;
  4516. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4517. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4518. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4519. return this;
  4520. }
  4521. /**
  4522. * Sets this matrix to the 3x3 identity matrix.
  4523. *
  4524. * @return {Matrix3} A reference to this matrix.
  4525. */
  4526. identity() {
  4527. this.set(
  4528. 1, 0, 0,
  4529. 0, 1, 0,
  4530. 0, 0, 1
  4531. );
  4532. return this;
  4533. }
  4534. /**
  4535. * Copies the values of the given matrix to this instance.
  4536. *
  4537. * @param {Matrix3} m - The matrix to copy.
  4538. * @return {Matrix3} A reference to this matrix.
  4539. */
  4540. copy( m ) {
  4541. const te = this.elements;
  4542. const me = m.elements;
  4543. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4544. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4545. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4546. return this;
  4547. }
  4548. /**
  4549. * Extracts the basis of this matrix into the three axis vectors provided.
  4550. *
  4551. * @param {Vector3} xAxis - The basis's x axis.
  4552. * @param {Vector3} yAxis - The basis's y axis.
  4553. * @param {Vector3} zAxis - The basis's z axis.
  4554. * @return {Matrix3} A reference to this matrix.
  4555. */
  4556. extractBasis( xAxis, yAxis, zAxis ) {
  4557. xAxis.setFromMatrix3Column( this, 0 );
  4558. yAxis.setFromMatrix3Column( this, 1 );
  4559. zAxis.setFromMatrix3Column( this, 2 );
  4560. return this;
  4561. }
  4562. /**
  4563. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4564. *
  4565. * @param {Matrix4} m - The 4x4 matrix.
  4566. * @return {Matrix3} A reference to this matrix.
  4567. */
  4568. setFromMatrix4( m ) {
  4569. const me = m.elements;
  4570. this.set(
  4571. me[ 0 ], me[ 4 ], me[ 8 ],
  4572. me[ 1 ], me[ 5 ], me[ 9 ],
  4573. me[ 2 ], me[ 6 ], me[ 10 ]
  4574. );
  4575. return this;
  4576. }
  4577. /**
  4578. * Post-multiplies this matrix by the given 3x3 matrix.
  4579. *
  4580. * @param {Matrix3} m - The matrix to multiply with.
  4581. * @return {Matrix3} A reference to this matrix.
  4582. */
  4583. multiply( m ) {
  4584. return this.multiplyMatrices( this, m );
  4585. }
  4586. /**
  4587. * Pre-multiplies this matrix by the given 3x3 matrix.
  4588. *
  4589. * @param {Matrix3} m - The matrix to multiply with.
  4590. * @return {Matrix3} A reference to this matrix.
  4591. */
  4592. premultiply( m ) {
  4593. return this.multiplyMatrices( m, this );
  4594. }
  4595. /**
  4596. * Multiples the given 3x3 matrices and stores the result
  4597. * in this matrix.
  4598. *
  4599. * @param {Matrix3} a - The first matrix.
  4600. * @param {Matrix3} b - The second matrix.
  4601. * @return {Matrix3} A reference to this matrix.
  4602. */
  4603. multiplyMatrices( a, b ) {
  4604. const ae = a.elements;
  4605. const be = b.elements;
  4606. const te = this.elements;
  4607. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4608. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4609. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4610. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4611. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4612. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4613. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4614. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4615. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4616. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4617. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4618. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4619. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4620. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4621. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4622. return this;
  4623. }
  4624. /**
  4625. * Multiplies every component of the matrix by the given scalar.
  4626. *
  4627. * @param {number} s - The scalar.
  4628. * @return {Matrix3} A reference to this matrix.
  4629. */
  4630. multiplyScalar( s ) {
  4631. const te = this.elements;
  4632. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4633. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4634. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4635. return this;
  4636. }
  4637. /**
  4638. * Computes and returns the determinant of this matrix.
  4639. *
  4640. * @return {number} The determinant.
  4641. */
  4642. determinant() {
  4643. const te = this.elements;
  4644. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4645. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4646. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4647. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4648. }
  4649. /**
  4650. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  4651. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4652. * a zero matrix instead.
  4653. *
  4654. * @return {Matrix3} A reference to this matrix.
  4655. */
  4656. invert() {
  4657. const te = this.elements,
  4658. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4659. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4660. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4661. t11 = n33 * n22 - n32 * n23,
  4662. t12 = n32 * n13 - n33 * n12,
  4663. t13 = n23 * n12 - n22 * n13,
  4664. det = n11 * t11 + n21 * t12 + n31 * t13;
  4665. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4666. const detInv = 1 / det;
  4667. te[ 0 ] = t11 * detInv;
  4668. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4669. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4670. te[ 3 ] = t12 * detInv;
  4671. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4672. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4673. te[ 6 ] = t13 * detInv;
  4674. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4675. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4676. return this;
  4677. }
  4678. /**
  4679. * Transposes this matrix in place.
  4680. *
  4681. * @return {Matrix3} A reference to this matrix.
  4682. */
  4683. transpose() {
  4684. let tmp;
  4685. const m = this.elements;
  4686. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4687. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4688. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4689. return this;
  4690. }
  4691. /**
  4692. * Computes the normal matrix which is the inverse transpose of the upper
  4693. * left 3x3 portion of the given 4x4 matrix.
  4694. *
  4695. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4696. * @return {Matrix3} A reference to this matrix.
  4697. */
  4698. getNormalMatrix( matrix4 ) {
  4699. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4700. }
  4701. /**
  4702. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4703. *
  4704. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4705. * @return {Matrix3} A reference to this matrix.
  4706. */
  4707. transposeIntoArray( r ) {
  4708. const m = this.elements;
  4709. r[ 0 ] = m[ 0 ];
  4710. r[ 1 ] = m[ 3 ];
  4711. r[ 2 ] = m[ 6 ];
  4712. r[ 3 ] = m[ 1 ];
  4713. r[ 4 ] = m[ 4 ];
  4714. r[ 5 ] = m[ 7 ];
  4715. r[ 6 ] = m[ 2 ];
  4716. r[ 7 ] = m[ 5 ];
  4717. r[ 8 ] = m[ 8 ];
  4718. return this;
  4719. }
  4720. /**
  4721. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4722. *
  4723. * @param {number} tx - Offset x.
  4724. * @param {number} ty - Offset y.
  4725. * @param {number} sx - Repeat x.
  4726. * @param {number} sy - Repeat y.
  4727. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4728. * @param {number} cx - Center x of rotation.
  4729. * @param {number} cy - Center y of rotation
  4730. * @return {Matrix3} A reference to this matrix.
  4731. */
  4732. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4733. const c = Math.cos( rotation );
  4734. const s = Math.sin( rotation );
  4735. this.set(
  4736. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4737. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4738. 0, 0, 1
  4739. );
  4740. return this;
  4741. }
  4742. /**
  4743. * Scales this matrix with the given scalar values.
  4744. *
  4745. * @param {number} sx - The amount to scale in the X axis.
  4746. * @param {number} sy - The amount to scale in the Y axis.
  4747. * @return {Matrix3} A reference to this matrix.
  4748. */
  4749. scale( sx, sy ) {
  4750. this.premultiply( _m3.makeScale( sx, sy ) );
  4751. return this;
  4752. }
  4753. /**
  4754. * Rotates this matrix by the given angle.
  4755. *
  4756. * @param {number} theta - The rotation in radians.
  4757. * @return {Matrix3} A reference to this matrix.
  4758. */
  4759. rotate( theta ) {
  4760. this.premultiply( _m3.makeRotation( - theta ) );
  4761. return this;
  4762. }
  4763. /**
  4764. * Translates this matrix by the given scalar values.
  4765. *
  4766. * @param {number} tx - The amount to translate in the X axis.
  4767. * @param {number} ty - The amount to translate in the Y axis.
  4768. * @return {Matrix3} A reference to this matrix.
  4769. */
  4770. translate( tx, ty ) {
  4771. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4772. return this;
  4773. }
  4774. // for 2D Transforms
  4775. /**
  4776. * Sets this matrix as a 2D translation transform.
  4777. *
  4778. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4779. * @param {number} y - The amount to translate in the Y axis.
  4780. * @return {Matrix3} A reference to this matrix.
  4781. */
  4782. makeTranslation( x, y ) {
  4783. if ( x.isVector2 ) {
  4784. this.set(
  4785. 1, 0, x.x,
  4786. 0, 1, x.y,
  4787. 0, 0, 1
  4788. );
  4789. } else {
  4790. this.set(
  4791. 1, 0, x,
  4792. 0, 1, y,
  4793. 0, 0, 1
  4794. );
  4795. }
  4796. return this;
  4797. }
  4798. /**
  4799. * Sets this matrix as a 2D rotational transformation.
  4800. *
  4801. * @param {number} theta - The rotation in radians.
  4802. * @return {Matrix3} A reference to this matrix.
  4803. */
  4804. makeRotation( theta ) {
  4805. // counterclockwise
  4806. const c = Math.cos( theta );
  4807. const s = Math.sin( theta );
  4808. this.set(
  4809. c, - s, 0,
  4810. s, c, 0,
  4811. 0, 0, 1
  4812. );
  4813. return this;
  4814. }
  4815. /**
  4816. * Sets this matrix as a 2D scale transform.
  4817. *
  4818. * @param {number} x - The amount to scale in the X axis.
  4819. * @param {number} y - The amount to scale in the Y axis.
  4820. * @return {Matrix3} A reference to this matrix.
  4821. */
  4822. makeScale( x, y ) {
  4823. this.set(
  4824. x, 0, 0,
  4825. 0, y, 0,
  4826. 0, 0, 1
  4827. );
  4828. return this;
  4829. }
  4830. /**
  4831. * Returns `true` if this matrix is equal with the given one.
  4832. *
  4833. * @param {Matrix3} matrix - The matrix to test for equality.
  4834. * @return {boolean} Whether this matrix is equal with the given one.
  4835. */
  4836. equals( matrix ) {
  4837. const te = this.elements;
  4838. const me = matrix.elements;
  4839. for ( let i = 0; i < 9; i ++ ) {
  4840. if ( te[ i ] !== me[ i ] ) return false;
  4841. }
  4842. return true;
  4843. }
  4844. /**
  4845. * Sets the elements of the matrix from the given array.
  4846. *
  4847. * @param {Array<number>} array - The matrix elements in column-major order.
  4848. * @param {number} [offset=0] - Index of the first element in the array.
  4849. * @return {Matrix3} A reference to this matrix.
  4850. */
  4851. fromArray( array, offset = 0 ) {
  4852. for ( let i = 0; i < 9; i ++ ) {
  4853. this.elements[ i ] = array[ i + offset ];
  4854. }
  4855. return this;
  4856. }
  4857. /**
  4858. * Writes the elements of this matrix to the given array. If no array is provided,
  4859. * the method returns a new instance.
  4860. *
  4861. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  4862. * @param {number} [offset=0] - Index of the first element in the array.
  4863. * @return {Array<number>} The matrix elements in column-major order.
  4864. */
  4865. toArray( array = [], offset = 0 ) {
  4866. const te = this.elements;
  4867. array[ offset ] = te[ 0 ];
  4868. array[ offset + 1 ] = te[ 1 ];
  4869. array[ offset + 2 ] = te[ 2 ];
  4870. array[ offset + 3 ] = te[ 3 ];
  4871. array[ offset + 4 ] = te[ 4 ];
  4872. array[ offset + 5 ] = te[ 5 ];
  4873. array[ offset + 6 ] = te[ 6 ];
  4874. array[ offset + 7 ] = te[ 7 ];
  4875. array[ offset + 8 ] = te[ 8 ];
  4876. return array;
  4877. }
  4878. /**
  4879. * Returns a matrix with copied values from this instance.
  4880. *
  4881. * @return {Matrix3} A clone of this instance.
  4882. */
  4883. clone() {
  4884. return new this.constructor().fromArray( this.elements );
  4885. }
  4886. }
  4887. const _m3 = /*@__PURE__*/ new Matrix3();
  4888. function arrayNeedsUint32( array ) {
  4889. // assumes larger values usually on last
  4890. for ( let i = array.length - 1; i >= 0; -- i ) {
  4891. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  4892. }
  4893. return false;
  4894. }
  4895. const TYPED_ARRAYS = {
  4896. Int8Array: Int8Array,
  4897. Uint8Array: Uint8Array,
  4898. Uint8ClampedArray: Uint8ClampedArray,
  4899. Int16Array: Int16Array,
  4900. Uint16Array: Uint16Array,
  4901. Int32Array: Int32Array,
  4902. Uint32Array: Uint32Array,
  4903. Float32Array: Float32Array,
  4904. Float64Array: Float64Array
  4905. };
  4906. function getTypedArray( type, buffer ) {
  4907. return new TYPED_ARRAYS[ type ]( buffer );
  4908. }
  4909. function createElementNS( name ) {
  4910. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  4911. }
  4912. function createCanvasElement() {
  4913. const canvas = createElementNS( 'canvas' );
  4914. canvas.style.display = 'block';
  4915. return canvas;
  4916. }
  4917. const _cache = {};
  4918. function warnOnce( message ) {
  4919. if ( message in _cache ) return;
  4920. _cache[ message ] = true;
  4921. console.warn( message );
  4922. }
  4923. function probeAsync( gl, sync, interval ) {
  4924. return new Promise( function ( resolve, reject ) {
  4925. function probe() {
  4926. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  4927. case gl.WAIT_FAILED:
  4928. reject();
  4929. break;
  4930. case gl.TIMEOUT_EXPIRED:
  4931. setTimeout( probe, interval );
  4932. break;
  4933. default:
  4934. resolve();
  4935. }
  4936. }
  4937. setTimeout( probe, interval );
  4938. } );
  4939. }
  4940. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  4941. 0.4123908, 0.3575843, 0.1804808,
  4942. 0.2126390, 0.7151687, 0.0721923,
  4943. 0.0193308, 0.1191948, 0.9505322
  4944. );
  4945. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  4946. 3.2409699, -1.5373832, -0.4986108,
  4947. -0.9692436, 1.8759675, 0.0415551,
  4948. 0.0556301, -0.203977, 1.0569715
  4949. );
  4950. function createColorManagement() {
  4951. const ColorManagement = {
  4952. enabled: true,
  4953. workingColorSpace: LinearSRGBColorSpace,
  4954. /**
  4955. * Implementations of supported color spaces.
  4956. *
  4957. * Required:
  4958. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  4959. * - whitePoint: reference white [ x y ]
  4960. * - transfer: transfer function (pre-defined)
  4961. * - toXYZ: Matrix3 RGB to XYZ transform
  4962. * - fromXYZ: Matrix3 XYZ to RGB transform
  4963. * - luminanceCoefficients: RGB luminance coefficients
  4964. *
  4965. * Optional:
  4966. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  4967. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  4968. *
  4969. * Reference:
  4970. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  4971. */
  4972. spaces: {},
  4973. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  4974. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  4975. return color;
  4976. }
  4977. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  4978. color.r = SRGBToLinear( color.r );
  4979. color.g = SRGBToLinear( color.g );
  4980. color.b = SRGBToLinear( color.b );
  4981. }
  4982. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  4983. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  4984. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  4985. }
  4986. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  4987. color.r = LinearToSRGB( color.r );
  4988. color.g = LinearToSRGB( color.g );
  4989. color.b = LinearToSRGB( color.b );
  4990. }
  4991. return color;
  4992. },
  4993. workingToColorSpace: function ( color, targetColorSpace ) {
  4994. return this.convert( color, this.workingColorSpace, targetColorSpace );
  4995. },
  4996. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  4997. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  4998. },
  4999. getPrimaries: function ( colorSpace ) {
  5000. return this.spaces[ colorSpace ].primaries;
  5001. },
  5002. getTransfer: function ( colorSpace ) {
  5003. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5004. return this.spaces[ colorSpace ].transfer;
  5005. },
  5006. getToneMappingMode: function ( colorSpace ) {
  5007. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5008. },
  5009. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5010. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5011. },
  5012. define: function ( colorSpaces ) {
  5013. Object.assign( this.spaces, colorSpaces );
  5014. },
  5015. // Internal APIs
  5016. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5017. return targetMatrix
  5018. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5019. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5020. },
  5021. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5022. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5023. },
  5024. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5025. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5026. },
  5027. // Deprecated
  5028. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5029. warnOnce( 'THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5030. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5031. },
  5032. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5033. warnOnce( 'THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5034. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5035. },
  5036. };
  5037. /******************************************************************************
  5038. * sRGB definitions
  5039. */
  5040. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5041. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5042. const D65 = [ 0.3127, 0.3290 ];
  5043. ColorManagement.define( {
  5044. [ LinearSRGBColorSpace ]: {
  5045. primaries: REC709_PRIMARIES,
  5046. whitePoint: D65,
  5047. transfer: LinearTransfer,
  5048. toXYZ: LINEAR_REC709_TO_XYZ,
  5049. fromXYZ: XYZ_TO_LINEAR_REC709,
  5050. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5051. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5052. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5053. },
  5054. [ SRGBColorSpace ]: {
  5055. primaries: REC709_PRIMARIES,
  5056. whitePoint: D65,
  5057. transfer: SRGBTransfer,
  5058. toXYZ: LINEAR_REC709_TO_XYZ,
  5059. fromXYZ: XYZ_TO_LINEAR_REC709,
  5060. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5061. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5062. },
  5063. } );
  5064. return ColorManagement;
  5065. }
  5066. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5067. function SRGBToLinear( c ) {
  5068. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5069. }
  5070. function LinearToSRGB( c ) {
  5071. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5072. }
  5073. let _canvas;
  5074. /**
  5075. * A class containing utility functions for images.
  5076. *
  5077. * @hideconstructor
  5078. */
  5079. class ImageUtils {
  5080. /**
  5081. * Returns a data URI containing a representation of the given image.
  5082. *
  5083. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5084. * @param {string} [type='image/png'] - Indicates the image format.
  5085. * @return {string} The data URI.
  5086. */
  5087. static getDataURL( image, type = 'image/png' ) {
  5088. if ( /^data:/i.test( image.src ) ) {
  5089. return image.src;
  5090. }
  5091. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5092. return image.src;
  5093. }
  5094. let canvas;
  5095. if ( image instanceof HTMLCanvasElement ) {
  5096. canvas = image;
  5097. } else {
  5098. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5099. _canvas.width = image.width;
  5100. _canvas.height = image.height;
  5101. const context = _canvas.getContext( '2d' );
  5102. if ( image instanceof ImageData ) {
  5103. context.putImageData( image, 0, 0 );
  5104. } else {
  5105. context.drawImage( image, 0, 0, image.width, image.height );
  5106. }
  5107. canvas = _canvas;
  5108. }
  5109. return canvas.toDataURL( type );
  5110. }
  5111. /**
  5112. * Converts the given sRGB image data to linear color space.
  5113. *
  5114. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5115. * @return {HTMLCanvasElement|Object} The converted image.
  5116. */
  5117. static sRGBToLinear( image ) {
  5118. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5119. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5120. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5121. const canvas = createElementNS( 'canvas' );
  5122. canvas.width = image.width;
  5123. canvas.height = image.height;
  5124. const context = canvas.getContext( '2d' );
  5125. context.drawImage( image, 0, 0, image.width, image.height );
  5126. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5127. const data = imageData.data;
  5128. for ( let i = 0; i < data.length; i ++ ) {
  5129. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5130. }
  5131. context.putImageData( imageData, 0, 0 );
  5132. return canvas;
  5133. } else if ( image.data ) {
  5134. const data = image.data.slice( 0 );
  5135. for ( let i = 0; i < data.length; i ++ ) {
  5136. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5137. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5138. } else {
  5139. // assuming float
  5140. data[ i ] = SRGBToLinear( data[ i ] );
  5141. }
  5142. }
  5143. return {
  5144. data: data,
  5145. width: image.width,
  5146. height: image.height
  5147. };
  5148. } else {
  5149. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5150. return image;
  5151. }
  5152. }
  5153. }
  5154. let _sourceId = 0;
  5155. /**
  5156. * Represents the data source of a texture.
  5157. *
  5158. * The main purpose of this class is to decouple the data definition from the texture
  5159. * definition so the same data can be used with multiple texture instances.
  5160. */
  5161. class Source {
  5162. /**
  5163. * Constructs a new video texture.
  5164. *
  5165. * @param {any} [data=null] - The data definition of a texture.
  5166. */
  5167. constructor( data = null ) {
  5168. /**
  5169. * This flag can be used for type testing.
  5170. *
  5171. * @type {boolean}
  5172. * @readonly
  5173. * @default true
  5174. */
  5175. this.isSource = true;
  5176. /**
  5177. * The ID of the source.
  5178. *
  5179. * @name Source#id
  5180. * @type {number}
  5181. * @readonly
  5182. */
  5183. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5184. /**
  5185. * The UUID of the source.
  5186. *
  5187. * @type {string}
  5188. * @readonly
  5189. */
  5190. this.uuid = generateUUID();
  5191. /**
  5192. * The data definition of a texture.
  5193. *
  5194. * @type {any}
  5195. */
  5196. this.data = data;
  5197. /**
  5198. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5199. * provides more control on how texture data should be processed. When `dataReady` is set
  5200. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5201. * the data into the GPU memory.
  5202. *
  5203. * @type {boolean}
  5204. * @default true
  5205. */
  5206. this.dataReady = true;
  5207. /**
  5208. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5209. *
  5210. * @type {number}
  5211. * @readonly
  5212. * @default 0
  5213. */
  5214. this.version = 0;
  5215. }
  5216. /**
  5217. * Returns the dimensions of the source into the given target vector.
  5218. *
  5219. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5220. * @return {(Vector2|Vector3)} The dimensions of the source.
  5221. */
  5222. getSize( target ) {
  5223. const data = this.data;
  5224. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5225. target.set( data.videoWidth, data.videoHeight, 0 );
  5226. } else if ( data instanceof VideoFrame ) {
  5227. target.set( data.displayHeight, data.displayWidth, 0 );
  5228. } else if ( data !== null ) {
  5229. target.set( data.width, data.height, data.depth || 0 );
  5230. } else {
  5231. target.set( 0, 0, 0 );
  5232. }
  5233. return target;
  5234. }
  5235. /**
  5236. * When the property is set to `true`, the engine allocates the memory
  5237. * for the texture (if necessary) and triggers the actual texture upload
  5238. * to the GPU next time the source is used.
  5239. *
  5240. * @type {boolean}
  5241. * @default false
  5242. * @param {boolean} value
  5243. */
  5244. set needsUpdate( value ) {
  5245. if ( value === true ) this.version ++;
  5246. }
  5247. /**
  5248. * Serializes the source into JSON.
  5249. *
  5250. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5251. * @return {Object} A JSON object representing the serialized source.
  5252. * @see {@link ObjectLoader#parse}
  5253. */
  5254. toJSON( meta ) {
  5255. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5256. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5257. return meta.images[ this.uuid ];
  5258. }
  5259. const output = {
  5260. uuid: this.uuid,
  5261. url: ''
  5262. };
  5263. const data = this.data;
  5264. if ( data !== null ) {
  5265. let url;
  5266. if ( Array.isArray( data ) ) {
  5267. // cube texture
  5268. url = [];
  5269. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5270. if ( data[ i ].isDataTexture ) {
  5271. url.push( serializeImage( data[ i ].image ) );
  5272. } else {
  5273. url.push( serializeImage( data[ i ] ) );
  5274. }
  5275. }
  5276. } else {
  5277. // texture
  5278. url = serializeImage( data );
  5279. }
  5280. output.url = url;
  5281. }
  5282. if ( ! isRootObject ) {
  5283. meta.images[ this.uuid ] = output;
  5284. }
  5285. return output;
  5286. }
  5287. }
  5288. function serializeImage( image ) {
  5289. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5290. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5291. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5292. // default images
  5293. return ImageUtils.getDataURL( image );
  5294. } else {
  5295. if ( image.data ) {
  5296. // images of DataTexture
  5297. return {
  5298. data: Array.from( image.data ),
  5299. width: image.width,
  5300. height: image.height,
  5301. type: image.data.constructor.name
  5302. };
  5303. } else {
  5304. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  5305. return {};
  5306. }
  5307. }
  5308. }
  5309. let _textureId = 0;
  5310. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5311. /**
  5312. * Base class for all textures.
  5313. *
  5314. * Note: After the initial use of a texture, its dimensions, format, and type
  5315. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5316. *
  5317. * @augments EventDispatcher
  5318. */
  5319. class Texture extends EventDispatcher {
  5320. /**
  5321. * Constructs a new texture.
  5322. *
  5323. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5324. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5325. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5326. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5327. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5328. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5329. * @param {number} [format=RGBAFormat] - The texture format.
  5330. * @param {number} [type=UnsignedByteType] - The texture type.
  5331. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5332. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5333. */
  5334. 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 ) {
  5335. super();
  5336. /**
  5337. * This flag can be used for type testing.
  5338. *
  5339. * @type {boolean}
  5340. * @readonly
  5341. * @default true
  5342. */
  5343. this.isTexture = true;
  5344. /**
  5345. * The ID of the texture.
  5346. *
  5347. * @name Texture#id
  5348. * @type {number}
  5349. * @readonly
  5350. */
  5351. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5352. /**
  5353. * The UUID of the material.
  5354. *
  5355. * @type {string}
  5356. * @readonly
  5357. */
  5358. this.uuid = generateUUID();
  5359. /**
  5360. * The name of the material.
  5361. *
  5362. * @type {string}
  5363. */
  5364. this.name = '';
  5365. /**
  5366. * The data definition of a texture. A reference to the data source can be
  5367. * shared across textures. This is often useful in context of spritesheets
  5368. * where multiple textures render the same data but with different texture
  5369. * transformations.
  5370. *
  5371. * @type {Source}
  5372. */
  5373. this.source = new Source( image );
  5374. /**
  5375. * An array holding user-defined mipmaps.
  5376. *
  5377. * @type {Array<Object>}
  5378. */
  5379. this.mipmaps = [];
  5380. /**
  5381. * How the texture is applied to the object. The value `UVMapping`
  5382. * is the default, where texture or uv coordinates are used to apply the map.
  5383. *
  5384. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5385. * @default UVMapping
  5386. */
  5387. this.mapping = mapping;
  5388. /**
  5389. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5390. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5391. *
  5392. * @type {number}
  5393. * @default 0
  5394. */
  5395. this.channel = 0;
  5396. /**
  5397. * This defines how the texture is wrapped horizontally and corresponds to
  5398. * *U* in UV mapping.
  5399. *
  5400. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5401. * @default ClampToEdgeWrapping
  5402. */
  5403. this.wrapS = wrapS;
  5404. /**
  5405. * This defines how the texture is wrapped horizontally and corresponds to
  5406. * *V* in UV mapping.
  5407. *
  5408. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5409. * @default ClampToEdgeWrapping
  5410. */
  5411. this.wrapT = wrapT;
  5412. /**
  5413. * How the texture is sampled when a texel covers more than one pixel.
  5414. *
  5415. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5416. * @default LinearFilter
  5417. */
  5418. this.magFilter = magFilter;
  5419. /**
  5420. * How the texture is sampled when a texel covers less than one pixel.
  5421. *
  5422. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5423. * @default LinearMipmapLinearFilter
  5424. */
  5425. this.minFilter = minFilter;
  5426. /**
  5427. * The number of samples taken along the axis through the pixel that has the
  5428. * highest density of texels. By default, this value is `1`. A higher value
  5429. * gives a less blurry result than a basic mipmap, at the cost of more
  5430. * texture samples being used.
  5431. *
  5432. * @type {number}
  5433. * @default 0
  5434. */
  5435. this.anisotropy = anisotropy;
  5436. /**
  5437. * The format of the texture.
  5438. *
  5439. * @type {number}
  5440. * @default RGBAFormat
  5441. */
  5442. this.format = format;
  5443. /**
  5444. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5445. * defines how the texture data is going to be stored on the GPU.
  5446. *
  5447. * This property allows to overwrite the default format.
  5448. *
  5449. * @type {?string}
  5450. * @default null
  5451. */
  5452. this.internalFormat = null;
  5453. /**
  5454. * The data type of the texture.
  5455. *
  5456. * @type {number}
  5457. * @default UnsignedByteType
  5458. */
  5459. this.type = type;
  5460. /**
  5461. * How much a single repetition of the texture is offset from the beginning,
  5462. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5463. *
  5464. * @type {Vector2}
  5465. * @default (0,0)
  5466. */
  5467. this.offset = new Vector2( 0, 0 );
  5468. /**
  5469. * How many times the texture is repeated across the surface, in each
  5470. * direction U and V. If repeat is set greater than `1` in either direction,
  5471. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5472. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5473. *
  5474. * @type {Vector2}
  5475. * @default (1,1)
  5476. */
  5477. this.repeat = new Vector2( 1, 1 );
  5478. /**
  5479. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5480. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5481. *
  5482. * @type {Vector2}
  5483. * @default (0,0)
  5484. */
  5485. this.center = new Vector2( 0, 0 );
  5486. /**
  5487. * How much the texture is rotated around the center point, in radians.
  5488. * Positive values are counter-clockwise.
  5489. *
  5490. * @type {number}
  5491. * @default 0
  5492. */
  5493. this.rotation = 0;
  5494. /**
  5495. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5496. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5497. * {@link Texture#rotation}, and {@link Texture#center}.
  5498. *
  5499. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5500. *
  5501. * @type {boolean}
  5502. * @default true
  5503. */
  5504. this.matrixAutoUpdate = true;
  5505. /**
  5506. * The uv-transformation matrix of the texture.
  5507. *
  5508. * @type {Matrix3}
  5509. */
  5510. this.matrix = new Matrix3();
  5511. /**
  5512. * Whether to generate mipmaps (if possible) for a texture.
  5513. *
  5514. * Set this to `false` if you are creating mipmaps manually.
  5515. *
  5516. * @type {boolean}
  5517. * @default true
  5518. */
  5519. this.generateMipmaps = true;
  5520. /**
  5521. * If set to `true`, the alpha channel, if present, is multiplied into the
  5522. * color channels when the texture is uploaded to the GPU.
  5523. *
  5524. * Note that this property has no effect when using `ImageBitmap`. You need to
  5525. * configure premultiply alpha on bitmap creation instead.
  5526. *
  5527. * @type {boolean}
  5528. * @default false
  5529. */
  5530. this.premultiplyAlpha = false;
  5531. /**
  5532. * If set to `true`, the texture is flipped along the vertical axis when
  5533. * uploaded to the GPU.
  5534. *
  5535. * Note that this property has no effect when using `ImageBitmap`. You need to
  5536. * configure the flip on bitmap creation instead.
  5537. *
  5538. * @type {boolean}
  5539. * @default true
  5540. */
  5541. this.flipY = true;
  5542. /**
  5543. * Specifies the alignment requirements for the start of each pixel row in memory.
  5544. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5545. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5546. *
  5547. * @type {number}
  5548. * @default 4
  5549. */
  5550. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5551. /**
  5552. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5553. *
  5554. * @type {string}
  5555. * @default NoColorSpace
  5556. */
  5557. this.colorSpace = colorSpace;
  5558. /**
  5559. * An object that can be used to store custom data about the texture. It
  5560. * should not hold references to functions as these will not be cloned.
  5561. *
  5562. * @type {Object}
  5563. */
  5564. this.userData = {};
  5565. /**
  5566. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5567. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5568. *
  5569. * @type {Array<Object>}
  5570. */
  5571. this.updateRanges = [];
  5572. /**
  5573. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5574. *
  5575. * @type {number}
  5576. * @readonly
  5577. * @default 0
  5578. */
  5579. this.version = 0;
  5580. /**
  5581. * A callback function, called when the texture is updated (e.g., when
  5582. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5583. *
  5584. * @type {?Function}
  5585. * @default null
  5586. */
  5587. this.onUpdate = null;
  5588. /**
  5589. * An optional back reference to the textures render target.
  5590. *
  5591. * @type {?(RenderTarget|WebGLRenderTarget)}
  5592. * @default null
  5593. */
  5594. this.renderTarget = null;
  5595. /**
  5596. * Indicates whether a texture belongs to a render target or not.
  5597. *
  5598. * @type {boolean}
  5599. * @readonly
  5600. * @default false
  5601. */
  5602. this.isRenderTargetTexture = false;
  5603. /**
  5604. * Indicates if a texture should be handled like a texture array.
  5605. *
  5606. * @type {boolean}
  5607. * @readonly
  5608. * @default false
  5609. */
  5610. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5611. /**
  5612. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5613. * (only relevant for render target textures).
  5614. *
  5615. * @type {number}
  5616. * @readonly
  5617. * @default 0
  5618. */
  5619. this.pmremVersion = 0;
  5620. }
  5621. /**
  5622. * The width of the texture in pixels.
  5623. */
  5624. get width() {
  5625. return this.source.getSize( _tempVec3 ).x;
  5626. }
  5627. /**
  5628. * The height of the texture in pixels.
  5629. */
  5630. get height() {
  5631. return this.source.getSize( _tempVec3 ).y;
  5632. }
  5633. /**
  5634. * The depth of the texture in pixels.
  5635. */
  5636. get depth() {
  5637. return this.source.getSize( _tempVec3 ).z;
  5638. }
  5639. /**
  5640. * The image object holding the texture data.
  5641. *
  5642. * @type {?Object}
  5643. */
  5644. get image() {
  5645. return this.source.data;
  5646. }
  5647. set image( value = null ) {
  5648. this.source.data = value;
  5649. }
  5650. /**
  5651. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5652. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5653. */
  5654. updateMatrix() {
  5655. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5656. }
  5657. /**
  5658. * Adds a range of data in the data texture to be updated on the GPU.
  5659. *
  5660. * @param {number} start - Position at which to start update.
  5661. * @param {number} count - The number of components to update.
  5662. */
  5663. addUpdateRange( start, count ) {
  5664. this.updateRanges.push( { start, count } );
  5665. }
  5666. /**
  5667. * Clears the update ranges.
  5668. */
  5669. clearUpdateRanges() {
  5670. this.updateRanges.length = 0;
  5671. }
  5672. /**
  5673. * Returns a new texture with copied values from this instance.
  5674. *
  5675. * @return {Texture} A clone of this instance.
  5676. */
  5677. clone() {
  5678. return new this.constructor().copy( this );
  5679. }
  5680. /**
  5681. * Copies the values of the given texture to this instance.
  5682. *
  5683. * @param {Texture} source - The texture to copy.
  5684. * @return {Texture} A reference to this instance.
  5685. */
  5686. copy( source ) {
  5687. this.name = source.name;
  5688. this.source = source.source;
  5689. this.mipmaps = source.mipmaps.slice( 0 );
  5690. this.mapping = source.mapping;
  5691. this.channel = source.channel;
  5692. this.wrapS = source.wrapS;
  5693. this.wrapT = source.wrapT;
  5694. this.magFilter = source.magFilter;
  5695. this.minFilter = source.minFilter;
  5696. this.anisotropy = source.anisotropy;
  5697. this.format = source.format;
  5698. this.internalFormat = source.internalFormat;
  5699. this.type = source.type;
  5700. this.offset.copy( source.offset );
  5701. this.repeat.copy( source.repeat );
  5702. this.center.copy( source.center );
  5703. this.rotation = source.rotation;
  5704. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5705. this.matrix.copy( source.matrix );
  5706. this.generateMipmaps = source.generateMipmaps;
  5707. this.premultiplyAlpha = source.premultiplyAlpha;
  5708. this.flipY = source.flipY;
  5709. this.unpackAlignment = source.unpackAlignment;
  5710. this.colorSpace = source.colorSpace;
  5711. this.renderTarget = source.renderTarget;
  5712. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5713. this.isArrayTexture = source.isArrayTexture;
  5714. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5715. this.needsUpdate = true;
  5716. return this;
  5717. }
  5718. /**
  5719. * Sets this texture's properties based on `values`.
  5720. * @param {Object} values - A container with texture parameters.
  5721. */
  5722. setValues( values ) {
  5723. for ( const key in values ) {
  5724. const newValue = values[ key ];
  5725. if ( newValue === undefined ) {
  5726. console.warn( `THREE.Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5727. continue;
  5728. }
  5729. const currentValue = this[ key ];
  5730. if ( currentValue === undefined ) {
  5731. console.warn( `THREE.Texture.setValues(): property '${ key }' does not exist.` );
  5732. continue;
  5733. }
  5734. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5735. currentValue.copy( newValue );
  5736. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5737. currentValue.copy( newValue );
  5738. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5739. currentValue.copy( newValue );
  5740. } else {
  5741. this[ key ] = newValue;
  5742. }
  5743. }
  5744. }
  5745. /**
  5746. * Serializes the texture into JSON.
  5747. *
  5748. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5749. * @return {Object} A JSON object representing the serialized texture.
  5750. * @see {@link ObjectLoader#parse}
  5751. */
  5752. toJSON( meta ) {
  5753. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5754. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5755. return meta.textures[ this.uuid ];
  5756. }
  5757. const output = {
  5758. metadata: {
  5759. version: 4.7,
  5760. type: 'Texture',
  5761. generator: 'Texture.toJSON'
  5762. },
  5763. uuid: this.uuid,
  5764. name: this.name,
  5765. image: this.source.toJSON( meta ).uuid,
  5766. mapping: this.mapping,
  5767. channel: this.channel,
  5768. repeat: [ this.repeat.x, this.repeat.y ],
  5769. offset: [ this.offset.x, this.offset.y ],
  5770. center: [ this.center.x, this.center.y ],
  5771. rotation: this.rotation,
  5772. wrap: [ this.wrapS, this.wrapT ],
  5773. format: this.format,
  5774. internalFormat: this.internalFormat,
  5775. type: this.type,
  5776. colorSpace: this.colorSpace,
  5777. minFilter: this.minFilter,
  5778. magFilter: this.magFilter,
  5779. anisotropy: this.anisotropy,
  5780. flipY: this.flipY,
  5781. generateMipmaps: this.generateMipmaps,
  5782. premultiplyAlpha: this.premultiplyAlpha,
  5783. unpackAlignment: this.unpackAlignment
  5784. };
  5785. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5786. if ( ! isRootObject ) {
  5787. meta.textures[ this.uuid ] = output;
  5788. }
  5789. return output;
  5790. }
  5791. /**
  5792. * Frees the GPU-related resources allocated by this instance. Call this
  5793. * method whenever this instance is no longer used in your app.
  5794. *
  5795. * @fires Texture#dispose
  5796. */
  5797. dispose() {
  5798. /**
  5799. * Fires when the texture has been disposed of.
  5800. *
  5801. * @event Texture#dispose
  5802. * @type {Object}
  5803. */
  5804. this.dispatchEvent( { type: 'dispose' } );
  5805. }
  5806. /**
  5807. * Transforms the given uv vector with the textures uv transformation matrix.
  5808. *
  5809. * @param {Vector2} uv - The uv vector.
  5810. * @return {Vector2} The transformed uv vector.
  5811. */
  5812. transformUv( uv ) {
  5813. if ( this.mapping !== UVMapping ) return uv;
  5814. uv.applyMatrix3( this.matrix );
  5815. if ( uv.x < 0 || uv.x > 1 ) {
  5816. switch ( this.wrapS ) {
  5817. case RepeatWrapping:
  5818. uv.x = uv.x - Math.floor( uv.x );
  5819. break;
  5820. case ClampToEdgeWrapping:
  5821. uv.x = uv.x < 0 ? 0 : 1;
  5822. break;
  5823. case MirroredRepeatWrapping:
  5824. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5825. uv.x = Math.ceil( uv.x ) - uv.x;
  5826. } else {
  5827. uv.x = uv.x - Math.floor( uv.x );
  5828. }
  5829. break;
  5830. }
  5831. }
  5832. if ( uv.y < 0 || uv.y > 1 ) {
  5833. switch ( this.wrapT ) {
  5834. case RepeatWrapping:
  5835. uv.y = uv.y - Math.floor( uv.y );
  5836. break;
  5837. case ClampToEdgeWrapping:
  5838. uv.y = uv.y < 0 ? 0 : 1;
  5839. break;
  5840. case MirroredRepeatWrapping:
  5841. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5842. uv.y = Math.ceil( uv.y ) - uv.y;
  5843. } else {
  5844. uv.y = uv.y - Math.floor( uv.y );
  5845. }
  5846. break;
  5847. }
  5848. }
  5849. if ( this.flipY ) {
  5850. uv.y = 1 - uv.y;
  5851. }
  5852. return uv;
  5853. }
  5854. /**
  5855. * Setting this property to `true` indicates the engine the texture
  5856. * must be updated in the next render. This triggers a texture upload
  5857. * to the GPU and ensures correct texture parameter configuration.
  5858. *
  5859. * @type {boolean}
  5860. * @default false
  5861. * @param {boolean} value
  5862. */
  5863. set needsUpdate( value ) {
  5864. if ( value === true ) {
  5865. this.version ++;
  5866. this.source.needsUpdate = true;
  5867. }
  5868. }
  5869. /**
  5870. * Setting this property to `true` indicates the engine the PMREM
  5871. * must be regenerated.
  5872. *
  5873. * @type {boolean}
  5874. * @default false
  5875. * @param {boolean} value
  5876. */
  5877. set needsPMREMUpdate( value ) {
  5878. if ( value === true ) {
  5879. this.pmremVersion ++;
  5880. }
  5881. }
  5882. }
  5883. /**
  5884. * The default image for all textures.
  5885. *
  5886. * @static
  5887. * @type {?Image}
  5888. * @default null
  5889. */
  5890. Texture.DEFAULT_IMAGE = null;
  5891. /**
  5892. * The default mapping for all textures.
  5893. *
  5894. * @static
  5895. * @type {number}
  5896. * @default UVMapping
  5897. */
  5898. Texture.DEFAULT_MAPPING = UVMapping;
  5899. /**
  5900. * The default anisotropy value for all textures.
  5901. *
  5902. * @static
  5903. * @type {number}
  5904. * @default 1
  5905. */
  5906. Texture.DEFAULT_ANISOTROPY = 1;
  5907. /**
  5908. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  5909. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  5910. *
  5911. * - A point in 4D space.
  5912. * - A direction and length in 4D space. In three.js the length will
  5913. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  5914. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  5915. * - Any arbitrary ordered quadruplet of numbers.
  5916. *
  5917. * There are other things a 4D vector can be used to represent, however these
  5918. * are the most common uses in *three.js*.
  5919. *
  5920. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  5921. * the corresponding order.
  5922. * ```js
  5923. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  5924. *
  5925. * //no arguments; will be initialised to (0, 0, 0, 1)
  5926. * const b = new THREE.Vector4( );
  5927. *
  5928. * const d = a.dot( b );
  5929. * ```
  5930. */
  5931. class Vector4 {
  5932. /**
  5933. * Constructs a new 4D vector.
  5934. *
  5935. * @param {number} [x=0] - The x value of this vector.
  5936. * @param {number} [y=0] - The y value of this vector.
  5937. * @param {number} [z=0] - The z value of this vector.
  5938. * @param {number} [w=1] - The w value of this vector.
  5939. */
  5940. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  5941. /**
  5942. * This flag can be used for type testing.
  5943. *
  5944. * @type {boolean}
  5945. * @readonly
  5946. * @default true
  5947. */
  5948. Vector4.prototype.isVector4 = true;
  5949. /**
  5950. * The x value of this vector.
  5951. *
  5952. * @type {number}
  5953. */
  5954. this.x = x;
  5955. /**
  5956. * The y value of this vector.
  5957. *
  5958. * @type {number}
  5959. */
  5960. this.y = y;
  5961. /**
  5962. * The z value of this vector.
  5963. *
  5964. * @type {number}
  5965. */
  5966. this.z = z;
  5967. /**
  5968. * The w value of this vector.
  5969. *
  5970. * @type {number}
  5971. */
  5972. this.w = w;
  5973. }
  5974. /**
  5975. * Alias for {@link Vector4#z}.
  5976. *
  5977. * @type {number}
  5978. */
  5979. get width() {
  5980. return this.z;
  5981. }
  5982. set width( value ) {
  5983. this.z = value;
  5984. }
  5985. /**
  5986. * Alias for {@link Vector4#w}.
  5987. *
  5988. * @type {number}
  5989. */
  5990. get height() {
  5991. return this.w;
  5992. }
  5993. set height( value ) {
  5994. this.w = value;
  5995. }
  5996. /**
  5997. * Sets the vector components.
  5998. *
  5999. * @param {number} x - The value of the x component.
  6000. * @param {number} y - The value of the y component.
  6001. * @param {number} z - The value of the z component.
  6002. * @param {number} w - The value of the w component.
  6003. * @return {Vector4} A reference to this vector.
  6004. */
  6005. set( x, y, z, w ) {
  6006. this.x = x;
  6007. this.y = y;
  6008. this.z = z;
  6009. this.w = w;
  6010. return this;
  6011. }
  6012. /**
  6013. * Sets the vector components to the same value.
  6014. *
  6015. * @param {number} scalar - The value to set for all vector components.
  6016. * @return {Vector4} A reference to this vector.
  6017. */
  6018. setScalar( scalar ) {
  6019. this.x = scalar;
  6020. this.y = scalar;
  6021. this.z = scalar;
  6022. this.w = scalar;
  6023. return this;
  6024. }
  6025. /**
  6026. * Sets the vector's x component to the given value
  6027. *
  6028. * @param {number} x - The value to set.
  6029. * @return {Vector4} A reference to this vector.
  6030. */
  6031. setX( x ) {
  6032. this.x = x;
  6033. return this;
  6034. }
  6035. /**
  6036. * Sets the vector's y component to the given value
  6037. *
  6038. * @param {number} y - The value to set.
  6039. * @return {Vector4} A reference to this vector.
  6040. */
  6041. setY( y ) {
  6042. this.y = y;
  6043. return this;
  6044. }
  6045. /**
  6046. * Sets the vector's z component to the given value
  6047. *
  6048. * @param {number} z - The value to set.
  6049. * @return {Vector4} A reference to this vector.
  6050. */
  6051. setZ( z ) {
  6052. this.z = z;
  6053. return this;
  6054. }
  6055. /**
  6056. * Sets the vector's w component to the given value
  6057. *
  6058. * @param {number} w - The value to set.
  6059. * @return {Vector4} A reference to this vector.
  6060. */
  6061. setW( w ) {
  6062. this.w = w;
  6063. return this;
  6064. }
  6065. /**
  6066. * Allows to set a vector component with an index.
  6067. *
  6068. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6069. * `2` equals to z, `3` equals to w.
  6070. * @param {number} value - The value to set.
  6071. * @return {Vector4} A reference to this vector.
  6072. */
  6073. setComponent( index, value ) {
  6074. switch ( index ) {
  6075. case 0: this.x = value; break;
  6076. case 1: this.y = value; break;
  6077. case 2: this.z = value; break;
  6078. case 3: this.w = value; break;
  6079. default: throw new Error( 'index is out of range: ' + index );
  6080. }
  6081. return this;
  6082. }
  6083. /**
  6084. * Returns the value of the vector component which matches the given index.
  6085. *
  6086. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6087. * `2` equals to z, `3` equals to w.
  6088. * @return {number} A vector component value.
  6089. */
  6090. getComponent( index ) {
  6091. switch ( index ) {
  6092. case 0: return this.x;
  6093. case 1: return this.y;
  6094. case 2: return this.z;
  6095. case 3: return this.w;
  6096. default: throw new Error( 'index is out of range: ' + index );
  6097. }
  6098. }
  6099. /**
  6100. * Returns a new vector with copied values from this instance.
  6101. *
  6102. * @return {Vector4} A clone of this instance.
  6103. */
  6104. clone() {
  6105. return new this.constructor( this.x, this.y, this.z, this.w );
  6106. }
  6107. /**
  6108. * Copies the values of the given vector to this instance.
  6109. *
  6110. * @param {Vector3|Vector4} v - The vector to copy.
  6111. * @return {Vector4} A reference to this vector.
  6112. */
  6113. copy( v ) {
  6114. this.x = v.x;
  6115. this.y = v.y;
  6116. this.z = v.z;
  6117. this.w = ( v.w !== undefined ) ? v.w : 1;
  6118. return this;
  6119. }
  6120. /**
  6121. * Adds the given vector to this instance.
  6122. *
  6123. * @param {Vector4} v - The vector to add.
  6124. * @return {Vector4} A reference to this vector.
  6125. */
  6126. add( v ) {
  6127. this.x += v.x;
  6128. this.y += v.y;
  6129. this.z += v.z;
  6130. this.w += v.w;
  6131. return this;
  6132. }
  6133. /**
  6134. * Adds the given scalar value to all components of this instance.
  6135. *
  6136. * @param {number} s - The scalar to add.
  6137. * @return {Vector4} A reference to this vector.
  6138. */
  6139. addScalar( s ) {
  6140. this.x += s;
  6141. this.y += s;
  6142. this.z += s;
  6143. this.w += s;
  6144. return this;
  6145. }
  6146. /**
  6147. * Adds the given vectors and stores the result in this instance.
  6148. *
  6149. * @param {Vector4} a - The first vector.
  6150. * @param {Vector4} b - The second vector.
  6151. * @return {Vector4} A reference to this vector.
  6152. */
  6153. addVectors( a, b ) {
  6154. this.x = a.x + b.x;
  6155. this.y = a.y + b.y;
  6156. this.z = a.z + b.z;
  6157. this.w = a.w + b.w;
  6158. return this;
  6159. }
  6160. /**
  6161. * Adds the given vector scaled by the given factor to this instance.
  6162. *
  6163. * @param {Vector4} v - The vector.
  6164. * @param {number} s - The factor that scales `v`.
  6165. * @return {Vector4} A reference to this vector.
  6166. */
  6167. addScaledVector( v, s ) {
  6168. this.x += v.x * s;
  6169. this.y += v.y * s;
  6170. this.z += v.z * s;
  6171. this.w += v.w * s;
  6172. return this;
  6173. }
  6174. /**
  6175. * Subtracts the given vector from this instance.
  6176. *
  6177. * @param {Vector4} v - The vector to subtract.
  6178. * @return {Vector4} A reference to this vector.
  6179. */
  6180. sub( v ) {
  6181. this.x -= v.x;
  6182. this.y -= v.y;
  6183. this.z -= v.z;
  6184. this.w -= v.w;
  6185. return this;
  6186. }
  6187. /**
  6188. * Subtracts the given scalar value from all components of this instance.
  6189. *
  6190. * @param {number} s - The scalar to subtract.
  6191. * @return {Vector4} A reference to this vector.
  6192. */
  6193. subScalar( s ) {
  6194. this.x -= s;
  6195. this.y -= s;
  6196. this.z -= s;
  6197. this.w -= s;
  6198. return this;
  6199. }
  6200. /**
  6201. * Subtracts the given vectors and stores the result in this instance.
  6202. *
  6203. * @param {Vector4} a - The first vector.
  6204. * @param {Vector4} b - The second vector.
  6205. * @return {Vector4} A reference to this vector.
  6206. */
  6207. subVectors( a, b ) {
  6208. this.x = a.x - b.x;
  6209. this.y = a.y - b.y;
  6210. this.z = a.z - b.z;
  6211. this.w = a.w - b.w;
  6212. return this;
  6213. }
  6214. /**
  6215. * Multiplies the given vector with this instance.
  6216. *
  6217. * @param {Vector4} v - The vector to multiply.
  6218. * @return {Vector4} A reference to this vector.
  6219. */
  6220. multiply( v ) {
  6221. this.x *= v.x;
  6222. this.y *= v.y;
  6223. this.z *= v.z;
  6224. this.w *= v.w;
  6225. return this;
  6226. }
  6227. /**
  6228. * Multiplies the given scalar value with all components of this instance.
  6229. *
  6230. * @param {number} scalar - The scalar to multiply.
  6231. * @return {Vector4} A reference to this vector.
  6232. */
  6233. multiplyScalar( scalar ) {
  6234. this.x *= scalar;
  6235. this.y *= scalar;
  6236. this.z *= scalar;
  6237. this.w *= scalar;
  6238. return this;
  6239. }
  6240. /**
  6241. * Multiplies this vector with the given 4x4 matrix.
  6242. *
  6243. * @param {Matrix4} m - The 4x4 matrix.
  6244. * @return {Vector4} A reference to this vector.
  6245. */
  6246. applyMatrix4( m ) {
  6247. const x = this.x, y = this.y, z = this.z, w = this.w;
  6248. const e = m.elements;
  6249. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6250. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6251. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6252. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6253. return this;
  6254. }
  6255. /**
  6256. * Divides this instance by the given vector.
  6257. *
  6258. * @param {Vector4} v - The vector to divide.
  6259. * @return {Vector4} A reference to this vector.
  6260. */
  6261. divide( v ) {
  6262. this.x /= v.x;
  6263. this.y /= v.y;
  6264. this.z /= v.z;
  6265. this.w /= v.w;
  6266. return this;
  6267. }
  6268. /**
  6269. * Divides this vector by the given scalar.
  6270. *
  6271. * @param {number} scalar - The scalar to divide.
  6272. * @return {Vector4} A reference to this vector.
  6273. */
  6274. divideScalar( scalar ) {
  6275. return this.multiplyScalar( 1 / scalar );
  6276. }
  6277. /**
  6278. * Sets the x, y and z components of this
  6279. * vector to the quaternion's axis and w to the angle.
  6280. *
  6281. * @param {Quaternion} q - The Quaternion to set.
  6282. * @return {Vector4} A reference to this vector.
  6283. */
  6284. setAxisAngleFromQuaternion( q ) {
  6285. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6286. // q is assumed to be normalized
  6287. this.w = 2 * Math.acos( q.w );
  6288. const s = Math.sqrt( 1 - q.w * q.w );
  6289. if ( s < 0.0001 ) {
  6290. this.x = 1;
  6291. this.y = 0;
  6292. this.z = 0;
  6293. } else {
  6294. this.x = q.x / s;
  6295. this.y = q.y / s;
  6296. this.z = q.z / s;
  6297. }
  6298. return this;
  6299. }
  6300. /**
  6301. * Sets the x, y and z components of this
  6302. * vector to the axis of rotation and w to the angle.
  6303. *
  6304. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6305. * @return {Vector4} A reference to this vector.
  6306. */
  6307. setAxisAngleFromRotationMatrix( m ) {
  6308. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6309. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6310. let angle, x, y, z; // variables for result
  6311. const epsilon = 0.01, // margin to allow for rounding errors
  6312. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6313. te = m.elements,
  6314. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6315. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6316. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6317. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6318. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6319. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6320. // singularity found
  6321. // first check for identity matrix which must have +1 for all terms
  6322. // in leading diagonal and zero in other terms
  6323. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6324. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6325. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6326. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6327. // this singularity is identity matrix so angle = 0
  6328. this.set( 1, 0, 0, 0 );
  6329. return this; // zero angle, arbitrary axis
  6330. }
  6331. // otherwise this singularity is angle = 180
  6332. angle = Math.PI;
  6333. const xx = ( m11 + 1 ) / 2;
  6334. const yy = ( m22 + 1 ) / 2;
  6335. const zz = ( m33 + 1 ) / 2;
  6336. const xy = ( m12 + m21 ) / 4;
  6337. const xz = ( m13 + m31 ) / 4;
  6338. const yz = ( m23 + m32 ) / 4;
  6339. if ( ( xx > yy ) && ( xx > zz ) ) {
  6340. // m11 is the largest diagonal term
  6341. if ( xx < epsilon ) {
  6342. x = 0;
  6343. y = 0.707106781;
  6344. z = 0.707106781;
  6345. } else {
  6346. x = Math.sqrt( xx );
  6347. y = xy / x;
  6348. z = xz / x;
  6349. }
  6350. } else if ( yy > zz ) {
  6351. // m22 is the largest diagonal term
  6352. if ( yy < epsilon ) {
  6353. x = 0.707106781;
  6354. y = 0;
  6355. z = 0.707106781;
  6356. } else {
  6357. y = Math.sqrt( yy );
  6358. x = xy / y;
  6359. z = yz / y;
  6360. }
  6361. } else {
  6362. // m33 is the largest diagonal term so base result on this
  6363. if ( zz < epsilon ) {
  6364. x = 0.707106781;
  6365. y = 0.707106781;
  6366. z = 0;
  6367. } else {
  6368. z = Math.sqrt( zz );
  6369. x = xz / z;
  6370. y = yz / z;
  6371. }
  6372. }
  6373. this.set( x, y, z, angle );
  6374. return this; // return 180 deg rotation
  6375. }
  6376. // as we have reached here there are no singularities so we can handle normally
  6377. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6378. ( m13 - m31 ) * ( m13 - m31 ) +
  6379. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6380. if ( Math.abs( s ) < 0.001 ) s = 1;
  6381. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6382. // caught by singularity test above, but I've left it in just in case
  6383. this.x = ( m32 - m23 ) / s;
  6384. this.y = ( m13 - m31 ) / s;
  6385. this.z = ( m21 - m12 ) / s;
  6386. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6387. return this;
  6388. }
  6389. /**
  6390. * Sets the vector components to the position elements of the
  6391. * given transformation matrix.
  6392. *
  6393. * @param {Matrix4} m - The 4x4 matrix.
  6394. * @return {Vector4} A reference to this vector.
  6395. */
  6396. setFromMatrixPosition( m ) {
  6397. const e = m.elements;
  6398. this.x = e[ 12 ];
  6399. this.y = e[ 13 ];
  6400. this.z = e[ 14 ];
  6401. this.w = e[ 15 ];
  6402. return this;
  6403. }
  6404. /**
  6405. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6406. * value, replace that value with the corresponding min value.
  6407. *
  6408. * @param {Vector4} v - The vector.
  6409. * @return {Vector4} A reference to this vector.
  6410. */
  6411. min( v ) {
  6412. this.x = Math.min( this.x, v.x );
  6413. this.y = Math.min( this.y, v.y );
  6414. this.z = Math.min( this.z, v.z );
  6415. this.w = Math.min( this.w, v.w );
  6416. return this;
  6417. }
  6418. /**
  6419. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6420. * value, replace that value with the corresponding max value.
  6421. *
  6422. * @param {Vector4} v - The vector.
  6423. * @return {Vector4} A reference to this vector.
  6424. */
  6425. max( v ) {
  6426. this.x = Math.max( this.x, v.x );
  6427. this.y = Math.max( this.y, v.y );
  6428. this.z = Math.max( this.z, v.z );
  6429. this.w = Math.max( this.w, v.w );
  6430. return this;
  6431. }
  6432. /**
  6433. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6434. * value, it is replaced by the corresponding value.
  6435. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6436. * it is replaced by the corresponding value.
  6437. *
  6438. * @param {Vector4} min - The minimum x, y and z values.
  6439. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6440. * @return {Vector4} A reference to this vector.
  6441. */
  6442. clamp( min, max ) {
  6443. // assumes min < max, componentwise
  6444. this.x = clamp( this.x, min.x, max.x );
  6445. this.y = clamp( this.y, min.y, max.y );
  6446. this.z = clamp( this.z, min.z, max.z );
  6447. this.w = clamp( this.w, min.w, max.w );
  6448. return this;
  6449. }
  6450. /**
  6451. * If this vector's x, y, z or w values are greater than the max value, they are
  6452. * replaced by the max value.
  6453. * If this vector's x, y, z or w values are less than the min value, they are
  6454. * replaced by the min value.
  6455. *
  6456. * @param {number} minVal - The minimum value the components will be clamped to.
  6457. * @param {number} maxVal - The maximum value the components will be clamped to.
  6458. * @return {Vector4} A reference to this vector.
  6459. */
  6460. clampScalar( minVal, maxVal ) {
  6461. this.x = clamp( this.x, minVal, maxVal );
  6462. this.y = clamp( this.y, minVal, maxVal );
  6463. this.z = clamp( this.z, minVal, maxVal );
  6464. this.w = clamp( this.w, minVal, maxVal );
  6465. return this;
  6466. }
  6467. /**
  6468. * If this vector's length is greater than the max value, it is replaced by
  6469. * the max value.
  6470. * If this vector's length is less than the min value, it is replaced by the
  6471. * min value.
  6472. *
  6473. * @param {number} min - The minimum value the vector length will be clamped to.
  6474. * @param {number} max - The maximum value the vector length will be clamped to.
  6475. * @return {Vector4} A reference to this vector.
  6476. */
  6477. clampLength( min, max ) {
  6478. const length = this.length();
  6479. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6480. }
  6481. /**
  6482. * The components of this vector are rounded down to the nearest integer value.
  6483. *
  6484. * @return {Vector4} A reference to this vector.
  6485. */
  6486. floor() {
  6487. this.x = Math.floor( this.x );
  6488. this.y = Math.floor( this.y );
  6489. this.z = Math.floor( this.z );
  6490. this.w = Math.floor( this.w );
  6491. return this;
  6492. }
  6493. /**
  6494. * The components of this vector are rounded up to the nearest integer value.
  6495. *
  6496. * @return {Vector4} A reference to this vector.
  6497. */
  6498. ceil() {
  6499. this.x = Math.ceil( this.x );
  6500. this.y = Math.ceil( this.y );
  6501. this.z = Math.ceil( this.z );
  6502. this.w = Math.ceil( this.w );
  6503. return this;
  6504. }
  6505. /**
  6506. * The components of this vector are rounded to the nearest integer value
  6507. *
  6508. * @return {Vector4} A reference to this vector.
  6509. */
  6510. round() {
  6511. this.x = Math.round( this.x );
  6512. this.y = Math.round( this.y );
  6513. this.z = Math.round( this.z );
  6514. this.w = Math.round( this.w );
  6515. return this;
  6516. }
  6517. /**
  6518. * The components of this vector are rounded towards zero (up if negative,
  6519. * down if positive) to an integer value.
  6520. *
  6521. * @return {Vector4} A reference to this vector.
  6522. */
  6523. roundToZero() {
  6524. this.x = Math.trunc( this.x );
  6525. this.y = Math.trunc( this.y );
  6526. this.z = Math.trunc( this.z );
  6527. this.w = Math.trunc( this.w );
  6528. return this;
  6529. }
  6530. /**
  6531. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6532. *
  6533. * @return {Vector4} A reference to this vector.
  6534. */
  6535. negate() {
  6536. this.x = - this.x;
  6537. this.y = - this.y;
  6538. this.z = - this.z;
  6539. this.w = - this.w;
  6540. return this;
  6541. }
  6542. /**
  6543. * Calculates the dot product of the given vector with this instance.
  6544. *
  6545. * @param {Vector4} v - The vector to compute the dot product with.
  6546. * @return {number} The result of the dot product.
  6547. */
  6548. dot( v ) {
  6549. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6550. }
  6551. /**
  6552. * Computes the square of the Euclidean length (straight-line length) from
  6553. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6554. * compare the length squared instead as it is slightly more efficient to calculate.
  6555. *
  6556. * @return {number} The square length of this vector.
  6557. */
  6558. lengthSq() {
  6559. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6560. }
  6561. /**
  6562. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6563. *
  6564. * @return {number} The length of this vector.
  6565. */
  6566. length() {
  6567. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6568. }
  6569. /**
  6570. * Computes the Manhattan length of this vector.
  6571. *
  6572. * @return {number} The length of this vector.
  6573. */
  6574. manhattanLength() {
  6575. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6576. }
  6577. /**
  6578. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6579. * with the same direction as this one, but with a vector length of `1`.
  6580. *
  6581. * @return {Vector4} A reference to this vector.
  6582. */
  6583. normalize() {
  6584. return this.divideScalar( this.length() || 1 );
  6585. }
  6586. /**
  6587. * Sets this vector to a vector with the same direction as this one, but
  6588. * with the specified length.
  6589. *
  6590. * @param {number} length - The new length of this vector.
  6591. * @return {Vector4} A reference to this vector.
  6592. */
  6593. setLength( length ) {
  6594. return this.normalize().multiplyScalar( length );
  6595. }
  6596. /**
  6597. * Linearly interpolates between the given vector and this instance, where
  6598. * alpha is the percent distance along the line - alpha = 0 will be this
  6599. * vector, and alpha = 1 will be the given one.
  6600. *
  6601. * @param {Vector4} v - The vector to interpolate towards.
  6602. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6603. * @return {Vector4} A reference to this vector.
  6604. */
  6605. lerp( v, alpha ) {
  6606. this.x += ( v.x - this.x ) * alpha;
  6607. this.y += ( v.y - this.y ) * alpha;
  6608. this.z += ( v.z - this.z ) * alpha;
  6609. this.w += ( v.w - this.w ) * alpha;
  6610. return this;
  6611. }
  6612. /**
  6613. * Linearly interpolates between the given vectors, where alpha is the percent
  6614. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6615. * be the second one. The result is stored in this instance.
  6616. *
  6617. * @param {Vector4} v1 - The first vector.
  6618. * @param {Vector4} v2 - The second vector.
  6619. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6620. * @return {Vector4} A reference to this vector.
  6621. */
  6622. lerpVectors( v1, v2, alpha ) {
  6623. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6624. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6625. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6626. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6627. return this;
  6628. }
  6629. /**
  6630. * Returns `true` if this vector is equal with the given one.
  6631. *
  6632. * @param {Vector4} v - The vector to test for equality.
  6633. * @return {boolean} Whether this vector is equal with the given one.
  6634. */
  6635. equals( v ) {
  6636. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6637. }
  6638. /**
  6639. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6640. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6641. *
  6642. * @param {Array<number>} array - An array holding the vector component values.
  6643. * @param {number} [offset=0] - The offset into the array.
  6644. * @return {Vector4} A reference to this vector.
  6645. */
  6646. fromArray( array, offset = 0 ) {
  6647. this.x = array[ offset ];
  6648. this.y = array[ offset + 1 ];
  6649. this.z = array[ offset + 2 ];
  6650. this.w = array[ offset + 3 ];
  6651. return this;
  6652. }
  6653. /**
  6654. * Writes the components of this vector to the given array. If no array is provided,
  6655. * the method returns a new instance.
  6656. *
  6657. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6658. * @param {number} [offset=0] - Index of the first element in the array.
  6659. * @return {Array<number>} The vector components.
  6660. */
  6661. toArray( array = [], offset = 0 ) {
  6662. array[ offset ] = this.x;
  6663. array[ offset + 1 ] = this.y;
  6664. array[ offset + 2 ] = this.z;
  6665. array[ offset + 3 ] = this.w;
  6666. return array;
  6667. }
  6668. /**
  6669. * Sets the components of this vector from the given buffer attribute.
  6670. *
  6671. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6672. * @param {number} index - The index into the attribute.
  6673. * @return {Vector4} A reference to this vector.
  6674. */
  6675. fromBufferAttribute( attribute, index ) {
  6676. this.x = attribute.getX( index );
  6677. this.y = attribute.getY( index );
  6678. this.z = attribute.getZ( index );
  6679. this.w = attribute.getW( index );
  6680. return this;
  6681. }
  6682. /**
  6683. * Sets each component of this vector to a pseudo-random value between `0` and
  6684. * `1`, excluding `1`.
  6685. *
  6686. * @return {Vector4} A reference to this vector.
  6687. */
  6688. random() {
  6689. this.x = Math.random();
  6690. this.y = Math.random();
  6691. this.z = Math.random();
  6692. this.w = Math.random();
  6693. return this;
  6694. }
  6695. *[ Symbol.iterator ]() {
  6696. yield this.x;
  6697. yield this.y;
  6698. yield this.z;
  6699. yield this.w;
  6700. }
  6701. }
  6702. /**
  6703. * A render target is a buffer where the video card draws pixels for a scene
  6704. * that is being rendered in the background. It is used in different effects,
  6705. * such as applying postprocessing to a rendered image before displaying it
  6706. * on the screen.
  6707. *
  6708. * @augments EventDispatcher
  6709. */
  6710. class RenderTarget extends EventDispatcher {
  6711. /**
  6712. * Render target options.
  6713. *
  6714. * @typedef {Object} RenderTarget~Options
  6715. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6716. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6717. * @property {number} [minFilter=LinearFilter] - The min filter.
  6718. * @property {number} [format=RGBAFormat] - The texture format.
  6719. * @property {number} [type=UnsignedByteType] - The texture type.
  6720. * @property {?string} [internalFormat=null] - The texture's internal format.
  6721. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6722. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6723. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6724. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6725. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6726. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6727. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6728. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6729. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6730. * @property {number} [samples=0] - The MSAA samples count.
  6731. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6732. * @property {number} [depth=1] - The texture depth.
  6733. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6734. */
  6735. /**
  6736. * Constructs a new render target.
  6737. *
  6738. * @param {number} [width=1] - The width of the render target.
  6739. * @param {number} [height=1] - The height of the render target.
  6740. * @param {RenderTarget~Options} [options] - The configuration object.
  6741. */
  6742. constructor( width = 1, height = 1, options = {} ) {
  6743. super();
  6744. options = Object.assign( {
  6745. generateMipmaps: false,
  6746. internalFormat: null,
  6747. minFilter: LinearFilter,
  6748. depthBuffer: true,
  6749. stencilBuffer: false,
  6750. resolveDepthBuffer: true,
  6751. resolveStencilBuffer: true,
  6752. depthTexture: null,
  6753. samples: 0,
  6754. count: 1,
  6755. depth: 1,
  6756. multiview: false
  6757. }, options );
  6758. /**
  6759. * This flag can be used for type testing.
  6760. *
  6761. * @type {boolean}
  6762. * @readonly
  6763. * @default true
  6764. */
  6765. this.isRenderTarget = true;
  6766. /**
  6767. * The width of the render target.
  6768. *
  6769. * @type {number}
  6770. * @default 1
  6771. */
  6772. this.width = width;
  6773. /**
  6774. * The height of the render target.
  6775. *
  6776. * @type {number}
  6777. * @default 1
  6778. */
  6779. this.height = height;
  6780. /**
  6781. * The depth of the render target.
  6782. *
  6783. * @type {number}
  6784. * @default 1
  6785. */
  6786. this.depth = options.depth;
  6787. /**
  6788. * A rectangular area inside the render target's viewport. Fragments that are
  6789. * outside the area will be discarded.
  6790. *
  6791. * @type {Vector4}
  6792. * @default (0,0,width,height)
  6793. */
  6794. this.scissor = new Vector4( 0, 0, width, height );
  6795. /**
  6796. * Indicates whether the scissor test should be enabled when rendering into
  6797. * this render target or not.
  6798. *
  6799. * @type {boolean}
  6800. * @default false
  6801. */
  6802. this.scissorTest = false;
  6803. /**
  6804. * A rectangular area representing the render target's viewport.
  6805. *
  6806. * @type {Vector4}
  6807. * @default (0,0,width,height)
  6808. */
  6809. this.viewport = new Vector4( 0, 0, width, height );
  6810. const image = { width: width, height: height, depth: options.depth };
  6811. const texture = new Texture( image );
  6812. /**
  6813. * An array of textures. Each color attachment is represented as a separate texture.
  6814. * Has at least a single entry for the default color attachment.
  6815. *
  6816. * @type {Array<Texture>}
  6817. */
  6818. this.textures = [];
  6819. const count = options.count;
  6820. for ( let i = 0; i < count; i ++ ) {
  6821. this.textures[ i ] = texture.clone();
  6822. this.textures[ i ].isRenderTargetTexture = true;
  6823. this.textures[ i ].renderTarget = this;
  6824. }
  6825. this._setTextureOptions( options );
  6826. /**
  6827. * Whether to allocate a depth buffer or not.
  6828. *
  6829. * @type {boolean}
  6830. * @default true
  6831. */
  6832. this.depthBuffer = options.depthBuffer;
  6833. /**
  6834. * Whether to allocate a stencil buffer or not.
  6835. *
  6836. * @type {boolean}
  6837. * @default false
  6838. */
  6839. this.stencilBuffer = options.stencilBuffer;
  6840. /**
  6841. * Whether to resolve the depth buffer or not.
  6842. *
  6843. * @type {boolean}
  6844. * @default true
  6845. */
  6846. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6847. /**
  6848. * Whether to resolve the stencil buffer or not.
  6849. *
  6850. * @type {boolean}
  6851. * @default true
  6852. */
  6853. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6854. this._depthTexture = null;
  6855. this.depthTexture = options.depthTexture;
  6856. /**
  6857. * The number of MSAA samples.
  6858. *
  6859. * A value of `0` disables MSAA.
  6860. *
  6861. * @type {number}
  6862. * @default 0
  6863. */
  6864. this.samples = options.samples;
  6865. /**
  6866. * Whether to this target is used in multiview rendering.
  6867. *
  6868. * @type {boolean}
  6869. * @default false
  6870. */
  6871. this.multiview = options.multiview;
  6872. }
  6873. _setTextureOptions( options = {} ) {
  6874. const values = {
  6875. minFilter: LinearFilter,
  6876. generateMipmaps: false,
  6877. flipY: false,
  6878. internalFormat: null
  6879. };
  6880. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6881. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6882. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6883. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6884. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6885. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6886. if ( options.format !== undefined ) values.format = options.format;
  6887. if ( options.type !== undefined ) values.type = options.type;
  6888. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6889. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6890. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6891. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6892. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6893. for ( let i = 0; i < this.textures.length; i ++ ) {
  6894. const texture = this.textures[ i ];
  6895. texture.setValues( values );
  6896. }
  6897. }
  6898. /**
  6899. * The texture representing the default color attachment.
  6900. *
  6901. * @type {Texture}
  6902. */
  6903. get texture() {
  6904. return this.textures[ 0 ];
  6905. }
  6906. set texture( value ) {
  6907. this.textures[ 0 ] = value;
  6908. }
  6909. set depthTexture( current ) {
  6910. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  6911. if ( current !== null ) current.renderTarget = this;
  6912. this._depthTexture = current;
  6913. }
  6914. /**
  6915. * Instead of saving the depth in a renderbuffer, a texture
  6916. * can be used instead which is useful for further processing
  6917. * e.g. in context of post-processing.
  6918. *
  6919. * @type {?DepthTexture}
  6920. * @default null
  6921. */
  6922. get depthTexture() {
  6923. return this._depthTexture;
  6924. }
  6925. /**
  6926. * Sets the size of this render target.
  6927. *
  6928. * @param {number} width - The width.
  6929. * @param {number} height - The height.
  6930. * @param {number} [depth=1] - The depth.
  6931. */
  6932. setSize( width, height, depth = 1 ) {
  6933. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  6934. this.width = width;
  6935. this.height = height;
  6936. this.depth = depth;
  6937. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  6938. this.textures[ i ].image.width = width;
  6939. this.textures[ i ].image.height = height;
  6940. this.textures[ i ].image.depth = depth;
  6941. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  6942. }
  6943. this.dispose();
  6944. }
  6945. this.viewport.set( 0, 0, width, height );
  6946. this.scissor.set( 0, 0, width, height );
  6947. }
  6948. /**
  6949. * Returns a new render target with copied values from this instance.
  6950. *
  6951. * @return {RenderTarget} A clone of this instance.
  6952. */
  6953. clone() {
  6954. return new this.constructor().copy( this );
  6955. }
  6956. /**
  6957. * Copies the settings of the given render target. This is a structural copy so
  6958. * no resources are shared between render targets after the copy. That includes
  6959. * all MRT textures and the depth texture.
  6960. *
  6961. * @param {RenderTarget} source - The render target to copy.
  6962. * @return {RenderTarget} A reference to this instance.
  6963. */
  6964. copy( source ) {
  6965. this.width = source.width;
  6966. this.height = source.height;
  6967. this.depth = source.depth;
  6968. this.scissor.copy( source.scissor );
  6969. this.scissorTest = source.scissorTest;
  6970. this.viewport.copy( source.viewport );
  6971. this.textures.length = 0;
  6972. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  6973. this.textures[ i ] = source.textures[ i ].clone();
  6974. this.textures[ i ].isRenderTargetTexture = true;
  6975. this.textures[ i ].renderTarget = this;
  6976. // ensure image object is not shared, see #20328
  6977. const image = Object.assign( {}, source.textures[ i ].image );
  6978. this.textures[ i ].source = new Source( image );
  6979. }
  6980. this.depthBuffer = source.depthBuffer;
  6981. this.stencilBuffer = source.stencilBuffer;
  6982. this.resolveDepthBuffer = source.resolveDepthBuffer;
  6983. this.resolveStencilBuffer = source.resolveStencilBuffer;
  6984. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  6985. this.samples = source.samples;
  6986. return this;
  6987. }
  6988. /**
  6989. * Frees the GPU-related resources allocated by this instance. Call this
  6990. * method whenever this instance is no longer used in your app.
  6991. *
  6992. * @fires RenderTarget#dispose
  6993. */
  6994. dispose() {
  6995. this.dispatchEvent( { type: 'dispose' } );
  6996. }
  6997. }
  6998. /**
  6999. * A render target used in context of {@link WebGLRenderer}.
  7000. *
  7001. * @augments RenderTarget
  7002. */
  7003. class WebGLRenderTarget extends RenderTarget {
  7004. /**
  7005. * Constructs a new 3D render target.
  7006. *
  7007. * @param {number} [width=1] - The width of the render target.
  7008. * @param {number} [height=1] - The height of the render target.
  7009. * @param {RenderTarget~Options} [options] - The configuration object.
  7010. */
  7011. constructor( width = 1, height = 1, options = {} ) {
  7012. super( width, height, options );
  7013. /**
  7014. * This flag can be used for type testing.
  7015. *
  7016. * @type {boolean}
  7017. * @readonly
  7018. * @default true
  7019. */
  7020. this.isWebGLRenderTarget = true;
  7021. }
  7022. }
  7023. /**
  7024. * Creates an array of textures directly from raw buffer data.
  7025. *
  7026. * @augments Texture
  7027. */
  7028. class DataArrayTexture extends Texture {
  7029. /**
  7030. * Constructs a new data array texture.
  7031. *
  7032. * @param {?TypedArray} [data=null] - The buffer data.
  7033. * @param {number} [width=1] - The width of the texture.
  7034. * @param {number} [height=1] - The height of the texture.
  7035. * @param {number} [depth=1] - The depth of the texture.
  7036. */
  7037. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7038. super( null );
  7039. /**
  7040. * This flag can be used for type testing.
  7041. *
  7042. * @type {boolean}
  7043. * @readonly
  7044. * @default true
  7045. */
  7046. this.isDataArrayTexture = true;
  7047. /**
  7048. * The image definition of a data texture.
  7049. *
  7050. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7051. */
  7052. this.image = { data, width, height, depth };
  7053. /**
  7054. * How the texture is sampled when a texel covers more than one pixel.
  7055. *
  7056. * Overwritten and set to `NearestFilter` by default.
  7057. *
  7058. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7059. * @default NearestFilter
  7060. */
  7061. this.magFilter = NearestFilter;
  7062. /**
  7063. * How the texture is sampled when a texel covers less than one pixel.
  7064. *
  7065. * Overwritten and set to `NearestFilter` by default.
  7066. *
  7067. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7068. * @default NearestFilter
  7069. */
  7070. this.minFilter = NearestFilter;
  7071. /**
  7072. * This defines how the texture is wrapped in the depth and corresponds to
  7073. * *W* in UVW mapping.
  7074. *
  7075. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7076. * @default ClampToEdgeWrapping
  7077. */
  7078. this.wrapR = ClampToEdgeWrapping;
  7079. /**
  7080. * Whether to generate mipmaps (if possible) for a texture.
  7081. *
  7082. * Overwritten and set to `false` by default.
  7083. *
  7084. * @type {boolean}
  7085. * @default false
  7086. */
  7087. this.generateMipmaps = false;
  7088. /**
  7089. * If set to `true`, the texture is flipped along the vertical axis when
  7090. * uploaded to the GPU.
  7091. *
  7092. * Overwritten and set to `false` by default.
  7093. *
  7094. * @type {boolean}
  7095. * @default false
  7096. */
  7097. this.flipY = false;
  7098. /**
  7099. * Specifies the alignment requirements for the start of each pixel row in memory.
  7100. *
  7101. * Overwritten and set to `1` by default.
  7102. *
  7103. * @type {boolean}
  7104. * @default 1
  7105. */
  7106. this.unpackAlignment = 1;
  7107. /**
  7108. * A set of all layers which need to be updated in the texture.
  7109. *
  7110. * @type {Set<number>}
  7111. */
  7112. this.layerUpdates = new Set();
  7113. }
  7114. /**
  7115. * Describes that a specific layer of the texture needs to be updated.
  7116. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7117. * entire data texture array is sent to the GPU. Marking specific
  7118. * layers will only transmit subsets of all mipmaps associated with a
  7119. * specific depth in the array which is often much more performant.
  7120. *
  7121. * @param {number} layerIndex - The layer index that should be updated.
  7122. */
  7123. addLayerUpdate( layerIndex ) {
  7124. this.layerUpdates.add( layerIndex );
  7125. }
  7126. /**
  7127. * Resets the layer updates registry.
  7128. */
  7129. clearLayerUpdates() {
  7130. this.layerUpdates.clear();
  7131. }
  7132. }
  7133. /**
  7134. * An array render target used in context of {@link WebGLRenderer}.
  7135. *
  7136. * @augments WebGLRenderTarget
  7137. */
  7138. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7139. /**
  7140. * Constructs a new array render target.
  7141. *
  7142. * @param {number} [width=1] - The width of the render target.
  7143. * @param {number} [height=1] - The height of the render target.
  7144. * @param {number} [depth=1] - The height of the render target.
  7145. * @param {RenderTarget~Options} [options] - The configuration object.
  7146. */
  7147. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7148. super( width, height, options );
  7149. /**
  7150. * This flag can be used for type testing.
  7151. *
  7152. * @type {boolean}
  7153. * @readonly
  7154. * @default true
  7155. */
  7156. this.isWebGLArrayRenderTarget = true;
  7157. this.depth = depth;
  7158. /**
  7159. * Overwritten with a different texture type.
  7160. *
  7161. * @type {DataArrayTexture}
  7162. */
  7163. this.texture = new DataArrayTexture( null, width, height, depth );
  7164. this._setTextureOptions( options );
  7165. this.texture.isRenderTargetTexture = true;
  7166. }
  7167. }
  7168. /**
  7169. * Creates a three-dimensional texture from raw data, with parameters to
  7170. * divide it into width, height, and depth.
  7171. *
  7172. * @augments Texture
  7173. */
  7174. class Data3DTexture extends Texture {
  7175. /**
  7176. * Constructs a new data array texture.
  7177. *
  7178. * @param {?TypedArray} [data=null] - The buffer data.
  7179. * @param {number} [width=1] - The width of the texture.
  7180. * @param {number} [height=1] - The height of the texture.
  7181. * @param {number} [depth=1] - The depth of the texture.
  7182. */
  7183. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7184. // We're going to add .setXXX() methods for setting properties later.
  7185. // Users can still set in Data3DTexture directly.
  7186. //
  7187. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7188. // texture.anisotropy = 16;
  7189. //
  7190. // See #14839
  7191. super( null );
  7192. /**
  7193. * This flag can be used for type testing.
  7194. *
  7195. * @type {boolean}
  7196. * @readonly
  7197. * @default true
  7198. */
  7199. this.isData3DTexture = true;
  7200. /**
  7201. * The image definition of a data texture.
  7202. *
  7203. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7204. */
  7205. this.image = { data, width, height, depth };
  7206. /**
  7207. * How the texture is sampled when a texel covers more than one pixel.
  7208. *
  7209. * Overwritten and set to `NearestFilter` by default.
  7210. *
  7211. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7212. * @default NearestFilter
  7213. */
  7214. this.magFilter = NearestFilter;
  7215. /**
  7216. * How the texture is sampled when a texel covers less than one pixel.
  7217. *
  7218. * Overwritten and set to `NearestFilter` by default.
  7219. *
  7220. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7221. * @default NearestFilter
  7222. */
  7223. this.minFilter = NearestFilter;
  7224. /**
  7225. * This defines how the texture is wrapped in the depth and corresponds to
  7226. * *W* in UVW mapping.
  7227. *
  7228. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7229. * @default ClampToEdgeWrapping
  7230. */
  7231. this.wrapR = ClampToEdgeWrapping;
  7232. /**
  7233. * Whether to generate mipmaps (if possible) for a texture.
  7234. *
  7235. * Overwritten and set to `false` by default.
  7236. *
  7237. * @type {boolean}
  7238. * @default false
  7239. */
  7240. this.generateMipmaps = false;
  7241. /**
  7242. * If set to `true`, the texture is flipped along the vertical axis when
  7243. * uploaded to the GPU.
  7244. *
  7245. * Overwritten and set to `false` by default.
  7246. *
  7247. * @type {boolean}
  7248. * @default false
  7249. */
  7250. this.flipY = false;
  7251. /**
  7252. * Specifies the alignment requirements for the start of each pixel row in memory.
  7253. *
  7254. * Overwritten and set to `1` by default.
  7255. *
  7256. * @type {boolean}
  7257. * @default 1
  7258. */
  7259. this.unpackAlignment = 1;
  7260. }
  7261. }
  7262. /**
  7263. * A 3D render target used in context of {@link WebGLRenderer}.
  7264. *
  7265. * @augments WebGLRenderTarget
  7266. */
  7267. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7268. /**
  7269. * Constructs a new 3D render target.
  7270. *
  7271. * @param {number} [width=1] - The width of the render target.
  7272. * @param {number} [height=1] - The height of the render target.
  7273. * @param {number} [depth=1] - The height of the render target.
  7274. * @param {RenderTarget~Options} [options] - The configuration object.
  7275. */
  7276. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7277. super( width, height, options );
  7278. /**
  7279. * This flag can be used for type testing.
  7280. *
  7281. * @type {boolean}
  7282. * @readonly
  7283. * @default true
  7284. */
  7285. this.isWebGL3DRenderTarget = true;
  7286. this.depth = depth;
  7287. /**
  7288. * Overwritten with a different texture type.
  7289. *
  7290. * @type {Data3DTexture}
  7291. */
  7292. this.texture = new Data3DTexture( null, width, height, depth );
  7293. this._setTextureOptions( options );
  7294. this.texture.isRenderTargetTexture = true;
  7295. }
  7296. }
  7297. /**
  7298. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7299. */
  7300. class Box3 {
  7301. /**
  7302. * Constructs a new bounding box.
  7303. *
  7304. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7305. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7306. */
  7307. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7308. /**
  7309. * This flag can be used for type testing.
  7310. *
  7311. * @type {boolean}
  7312. * @readonly
  7313. * @default true
  7314. */
  7315. this.isBox3 = true;
  7316. /**
  7317. * The lower boundary of the box.
  7318. *
  7319. * @type {Vector3}
  7320. */
  7321. this.min = min;
  7322. /**
  7323. * The upper boundary of the box.
  7324. *
  7325. * @type {Vector3}
  7326. */
  7327. this.max = max;
  7328. }
  7329. /**
  7330. * Sets the lower and upper boundaries of this box.
  7331. * Please note that this method only copies the values from the given objects.
  7332. *
  7333. * @param {Vector3} min - The lower boundary of the box.
  7334. * @param {Vector3} max - The upper boundary of the box.
  7335. * @return {Box3} A reference to this bounding box.
  7336. */
  7337. set( min, max ) {
  7338. this.min.copy( min );
  7339. this.max.copy( max );
  7340. return this;
  7341. }
  7342. /**
  7343. * Sets the upper and lower bounds of this box so it encloses the position data
  7344. * in the given array.
  7345. *
  7346. * @param {Array<number>} array - An array holding 3D position data.
  7347. * @return {Box3} A reference to this bounding box.
  7348. */
  7349. setFromArray( array ) {
  7350. this.makeEmpty();
  7351. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7352. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7353. }
  7354. return this;
  7355. }
  7356. /**
  7357. * Sets the upper and lower bounds of this box so it encloses the position data
  7358. * in the given buffer attribute.
  7359. *
  7360. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7361. * @return {Box3} A reference to this bounding box.
  7362. */
  7363. setFromBufferAttribute( attribute ) {
  7364. this.makeEmpty();
  7365. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7366. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7367. }
  7368. return this;
  7369. }
  7370. /**
  7371. * Sets the upper and lower bounds of this box so it encloses the position data
  7372. * in the given array.
  7373. *
  7374. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7375. * @return {Box3} A reference to this bounding box.
  7376. */
  7377. setFromPoints( points ) {
  7378. this.makeEmpty();
  7379. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7380. this.expandByPoint( points[ i ] );
  7381. }
  7382. return this;
  7383. }
  7384. /**
  7385. * Centers this box on the given center vector and sets this box's width, height and
  7386. * depth to the given size values.
  7387. *
  7388. * @param {Vector3} center - The center of the box.
  7389. * @param {Vector3} size - The x, y and z dimensions of the box.
  7390. * @return {Box3} A reference to this bounding box.
  7391. */
  7392. setFromCenterAndSize( center, size ) {
  7393. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7394. this.min.copy( center ).sub( halfSize );
  7395. this.max.copy( center ).add( halfSize );
  7396. return this;
  7397. }
  7398. /**
  7399. * Computes the world-axis-aligned bounding box for the given 3D object
  7400. * (including its children), accounting for the object's, and children's,
  7401. * world transforms. The function may result in a larger box than strictly necessary.
  7402. *
  7403. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7404. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7405. * world-axis-aligned bounding box at the expense of more computation.
  7406. * @return {Box3} A reference to this bounding box.
  7407. */
  7408. setFromObject( object, precise = false ) {
  7409. this.makeEmpty();
  7410. return this.expandByObject( object, precise );
  7411. }
  7412. /**
  7413. * Returns a new box with copied values from this instance.
  7414. *
  7415. * @return {Box3} A clone of this instance.
  7416. */
  7417. clone() {
  7418. return new this.constructor().copy( this );
  7419. }
  7420. /**
  7421. * Copies the values of the given box to this instance.
  7422. *
  7423. * @param {Box3} box - The box to copy.
  7424. * @return {Box3} A reference to this bounding box.
  7425. */
  7426. copy( box ) {
  7427. this.min.copy( box.min );
  7428. this.max.copy( box.max );
  7429. return this;
  7430. }
  7431. /**
  7432. * Makes this box empty which means in encloses a zero space in 3D.
  7433. *
  7434. * @return {Box3} A reference to this bounding box.
  7435. */
  7436. makeEmpty() {
  7437. this.min.x = this.min.y = this.min.z = + Infinity;
  7438. this.max.x = this.max.y = this.max.z = - Infinity;
  7439. return this;
  7440. }
  7441. /**
  7442. * Returns true if this box includes zero points within its bounds.
  7443. * Note that a box with equal lower and upper bounds still includes one
  7444. * point, the one both bounds share.
  7445. *
  7446. * @return {boolean} Whether this box is empty or not.
  7447. */
  7448. isEmpty() {
  7449. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7450. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7451. }
  7452. /**
  7453. * Returns the center point of this box.
  7454. *
  7455. * @param {Vector3} target - The target vector that is used to store the method's result.
  7456. * @return {Vector3} The center point.
  7457. */
  7458. getCenter( target ) {
  7459. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7460. }
  7461. /**
  7462. * Returns the dimensions of this box.
  7463. *
  7464. * @param {Vector3} target - The target vector that is used to store the method's result.
  7465. * @return {Vector3} The size.
  7466. */
  7467. getSize( target ) {
  7468. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7469. }
  7470. /**
  7471. * Expands the boundaries of this box to include the given point.
  7472. *
  7473. * @param {Vector3} point - The point that should be included by the bounding box.
  7474. * @return {Box3} A reference to this bounding box.
  7475. */
  7476. expandByPoint( point ) {
  7477. this.min.min( point );
  7478. this.max.max( point );
  7479. return this;
  7480. }
  7481. /**
  7482. * Expands this box equilaterally by the given vector. The width of this
  7483. * box will be expanded by the x component of the vector in both
  7484. * directions. The height of this box will be expanded by the y component of
  7485. * the vector in both directions. The depth of this box will be
  7486. * expanded by the z component of the vector in both directions.
  7487. *
  7488. * @param {Vector3} vector - The vector that should expand the bounding box.
  7489. * @return {Box3} A reference to this bounding box.
  7490. */
  7491. expandByVector( vector ) {
  7492. this.min.sub( vector );
  7493. this.max.add( vector );
  7494. return this;
  7495. }
  7496. /**
  7497. * Expands each dimension of the box by the given scalar. If negative, the
  7498. * dimensions of the box will be contracted.
  7499. *
  7500. * @param {number} scalar - The scalar value that should expand the bounding box.
  7501. * @return {Box3} A reference to this bounding box.
  7502. */
  7503. expandByScalar( scalar ) {
  7504. this.min.addScalar( - scalar );
  7505. this.max.addScalar( scalar );
  7506. return this;
  7507. }
  7508. /**
  7509. * Expands the boundaries of this box to include the given 3D object and
  7510. * its children, accounting for the object's, and children's, world
  7511. * transforms. The function may result in a larger box than strictly
  7512. * necessary (unless the precise parameter is set to true).
  7513. *
  7514. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7515. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7516. * as little as necessary at the expense of more computation.
  7517. * @return {Box3} A reference to this bounding box.
  7518. */
  7519. expandByObject( object, precise = false ) {
  7520. // Computes the world-axis-aligned bounding box of an object (including its children),
  7521. // accounting for both the object's, and children's, world transforms
  7522. object.updateWorldMatrix( false, false );
  7523. const geometry = object.geometry;
  7524. if ( geometry !== undefined ) {
  7525. const positionAttribute = geometry.getAttribute( 'position' );
  7526. // precise AABB computation based on vertex data requires at least a position attribute.
  7527. // instancing isn't supported so far and uses the normal (conservative) code path.
  7528. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7529. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7530. if ( object.isMesh === true ) {
  7531. object.getVertexPosition( i, _vector$b );
  7532. } else {
  7533. _vector$b.fromBufferAttribute( positionAttribute, i );
  7534. }
  7535. _vector$b.applyMatrix4( object.matrixWorld );
  7536. this.expandByPoint( _vector$b );
  7537. }
  7538. } else {
  7539. if ( object.boundingBox !== undefined ) {
  7540. // object-level bounding box
  7541. if ( object.boundingBox === null ) {
  7542. object.computeBoundingBox();
  7543. }
  7544. _box$4.copy( object.boundingBox );
  7545. } else {
  7546. // geometry-level bounding box
  7547. if ( geometry.boundingBox === null ) {
  7548. geometry.computeBoundingBox();
  7549. }
  7550. _box$4.copy( geometry.boundingBox );
  7551. }
  7552. _box$4.applyMatrix4( object.matrixWorld );
  7553. this.union( _box$4 );
  7554. }
  7555. }
  7556. const children = object.children;
  7557. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7558. this.expandByObject( children[ i ], precise );
  7559. }
  7560. return this;
  7561. }
  7562. /**
  7563. * Returns `true` if the given point lies within or on the boundaries of this box.
  7564. *
  7565. * @param {Vector3} point - The point to test.
  7566. * @return {boolean} Whether the bounding box contains the given point or not.
  7567. */
  7568. containsPoint( point ) {
  7569. return point.x >= this.min.x && point.x <= this.max.x &&
  7570. point.y >= this.min.y && point.y <= this.max.y &&
  7571. point.z >= this.min.z && point.z <= this.max.z;
  7572. }
  7573. /**
  7574. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7575. * If this box and the given one are identical, this function also returns `true`.
  7576. *
  7577. * @param {Box3} box - The bounding box to test.
  7578. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7579. */
  7580. containsBox( box ) {
  7581. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7582. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7583. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7584. }
  7585. /**
  7586. * Returns a point as a proportion of this box's width, height and depth.
  7587. *
  7588. * @param {Vector3} point - A point in 3D space.
  7589. * @param {Vector3} target - The target vector that is used to store the method's result.
  7590. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7591. */
  7592. getParameter( point, target ) {
  7593. // This can potentially have a divide by zero if the box
  7594. // has a size dimension of 0.
  7595. return target.set(
  7596. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7597. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7598. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7599. );
  7600. }
  7601. /**
  7602. * Returns `true` if the given bounding box intersects with this bounding box.
  7603. *
  7604. * @param {Box3} box - The bounding box to test.
  7605. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7606. */
  7607. intersectsBox( box ) {
  7608. // using 6 splitting planes to rule out intersections.
  7609. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7610. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7611. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7612. }
  7613. /**
  7614. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7615. *
  7616. * @param {Sphere} sphere - The bounding sphere to test.
  7617. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7618. */
  7619. intersectsSphere( sphere ) {
  7620. // Find the point on the AABB closest to the sphere center.
  7621. this.clampPoint( sphere.center, _vector$b );
  7622. // If that point is inside the sphere, the AABB and sphere intersect.
  7623. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7624. }
  7625. /**
  7626. * Returns `true` if the given plane intersects with this bounding box.
  7627. *
  7628. * @param {Plane} plane - The plane to test.
  7629. * @return {boolean} Whether the given plane intersects with this bounding box.
  7630. */
  7631. intersectsPlane( plane ) {
  7632. // We compute the minimum and maximum dot product values. If those values
  7633. // are on the same side (back or front) of the plane, then there is no intersection.
  7634. let min, max;
  7635. if ( plane.normal.x > 0 ) {
  7636. min = plane.normal.x * this.min.x;
  7637. max = plane.normal.x * this.max.x;
  7638. } else {
  7639. min = plane.normal.x * this.max.x;
  7640. max = plane.normal.x * this.min.x;
  7641. }
  7642. if ( plane.normal.y > 0 ) {
  7643. min += plane.normal.y * this.min.y;
  7644. max += plane.normal.y * this.max.y;
  7645. } else {
  7646. min += plane.normal.y * this.max.y;
  7647. max += plane.normal.y * this.min.y;
  7648. }
  7649. if ( plane.normal.z > 0 ) {
  7650. min += plane.normal.z * this.min.z;
  7651. max += plane.normal.z * this.max.z;
  7652. } else {
  7653. min += plane.normal.z * this.max.z;
  7654. max += plane.normal.z * this.min.z;
  7655. }
  7656. return ( min <= - plane.constant && max >= - plane.constant );
  7657. }
  7658. /**
  7659. * Returns `true` if the given triangle intersects with this bounding box.
  7660. *
  7661. * @param {Triangle} triangle - The triangle to test.
  7662. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7663. */
  7664. intersectsTriangle( triangle ) {
  7665. if ( this.isEmpty() ) {
  7666. return false;
  7667. }
  7668. // compute box center and extents
  7669. this.getCenter( _center );
  7670. _extents.subVectors( this.max, _center );
  7671. // translate triangle to aabb origin
  7672. _v0$2.subVectors( triangle.a, _center );
  7673. _v1$7.subVectors( triangle.b, _center );
  7674. _v2$4.subVectors( triangle.c, _center );
  7675. // compute edge vectors for triangle
  7676. _f0.subVectors( _v1$7, _v0$2 );
  7677. _f1.subVectors( _v2$4, _v1$7 );
  7678. _f2.subVectors( _v0$2, _v2$4 );
  7679. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7680. // 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
  7681. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7682. let axes = [
  7683. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7684. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7685. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7686. ];
  7687. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7688. return false;
  7689. }
  7690. // test 3 face normals from the aabb
  7691. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7692. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7693. return false;
  7694. }
  7695. // finally testing the face normal of the triangle
  7696. // use already existing triangle edge vectors here
  7697. _triangleNormal.crossVectors( _f0, _f1 );
  7698. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7699. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  7700. }
  7701. /**
  7702. * Clamps the given point within the bounds of this box.
  7703. *
  7704. * @param {Vector3} point - The point to clamp.
  7705. * @param {Vector3} target - The target vector that is used to store the method's result.
  7706. * @return {Vector3} The clamped point.
  7707. */
  7708. clampPoint( point, target ) {
  7709. return target.copy( point ).clamp( this.min, this.max );
  7710. }
  7711. /**
  7712. * Returns the euclidean distance from any edge of this box to the specified point. If
  7713. * the given point lies inside of this box, the distance will be `0`.
  7714. *
  7715. * @param {Vector3} point - The point to compute the distance to.
  7716. * @return {number} The euclidean distance.
  7717. */
  7718. distanceToPoint( point ) {
  7719. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7720. }
  7721. /**
  7722. * Returns a bounding sphere that encloses this bounding box.
  7723. *
  7724. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7725. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7726. */
  7727. getBoundingSphere( target ) {
  7728. if ( this.isEmpty() ) {
  7729. target.makeEmpty();
  7730. } else {
  7731. this.getCenter( target.center );
  7732. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7733. }
  7734. return target;
  7735. }
  7736. /**
  7737. * Computes the intersection of this bounding box and the given one, setting the upper
  7738. * bound of this box to the lesser of the two boxes' upper bounds and the
  7739. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7740. * there's no overlap, makes this box empty.
  7741. *
  7742. * @param {Box3} box - The bounding box to intersect with.
  7743. * @return {Box3} A reference to this bounding box.
  7744. */
  7745. intersect( box ) {
  7746. this.min.max( box.min );
  7747. this.max.min( box.max );
  7748. // 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.
  7749. if ( this.isEmpty() ) this.makeEmpty();
  7750. return this;
  7751. }
  7752. /**
  7753. * Computes the union of this box and another and the given one, setting the upper
  7754. * bound of this box to the greater of the two boxes' upper bounds and the
  7755. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7756. *
  7757. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7758. * @return {Box3} A reference to this bounding box.
  7759. */
  7760. union( box ) {
  7761. this.min.min( box.min );
  7762. this.max.max( box.max );
  7763. return this;
  7764. }
  7765. /**
  7766. * Transforms this bounding box by the given 4x4 transformation matrix.
  7767. *
  7768. * @param {Matrix4} matrix - The transformation matrix.
  7769. * @return {Box3} A reference to this bounding box.
  7770. */
  7771. applyMatrix4( matrix ) {
  7772. // transform of empty box is an empty box.
  7773. if ( this.isEmpty() ) return this;
  7774. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7775. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7776. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7777. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7778. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7779. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7780. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7781. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7782. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7783. this.setFromPoints( _points );
  7784. return this;
  7785. }
  7786. /**
  7787. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7788. * effectively moving it in 3D space.
  7789. *
  7790. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7791. * @return {Box3} A reference to this bounding box.
  7792. */
  7793. translate( offset ) {
  7794. this.min.add( offset );
  7795. this.max.add( offset );
  7796. return this;
  7797. }
  7798. /**
  7799. * Returns `true` if this bounding box is equal with the given one.
  7800. *
  7801. * @param {Box3} box - The box to test for equality.
  7802. * @return {boolean} Whether this bounding box is equal with the given one.
  7803. */
  7804. equals( box ) {
  7805. return box.min.equals( this.min ) && box.max.equals( this.max );
  7806. }
  7807. /**
  7808. * Returns a serialized structure of the bounding box.
  7809. *
  7810. * @return {Object} Serialized structure with fields representing the object state.
  7811. */
  7812. toJSON() {
  7813. return {
  7814. min: this.min.toArray(),
  7815. max: this.max.toArray()
  7816. };
  7817. }
  7818. /**
  7819. * Returns a serialized structure of the bounding box.
  7820. *
  7821. * @param {Object} json - The serialized json to set the box from.
  7822. * @return {Box3} A reference to this bounding box.
  7823. */
  7824. fromJSON( json ) {
  7825. this.min.fromArray( json.min );
  7826. this.max.fromArray( json.max );
  7827. return this;
  7828. }
  7829. }
  7830. const _points = [
  7831. /*@__PURE__*/ new Vector3(),
  7832. /*@__PURE__*/ new Vector3(),
  7833. /*@__PURE__*/ new Vector3(),
  7834. /*@__PURE__*/ new Vector3(),
  7835. /*@__PURE__*/ new Vector3(),
  7836. /*@__PURE__*/ new Vector3(),
  7837. /*@__PURE__*/ new Vector3(),
  7838. /*@__PURE__*/ new Vector3()
  7839. ];
  7840. const _vector$b = /*@__PURE__*/ new Vector3();
  7841. const _box$4 = /*@__PURE__*/ new Box3();
  7842. // triangle centered vertices
  7843. const _v0$2 = /*@__PURE__*/ new Vector3();
  7844. const _v1$7 = /*@__PURE__*/ new Vector3();
  7845. const _v2$4 = /*@__PURE__*/ new Vector3();
  7846. // triangle edge vectors
  7847. const _f0 = /*@__PURE__*/ new Vector3();
  7848. const _f1 = /*@__PURE__*/ new Vector3();
  7849. const _f2 = /*@__PURE__*/ new Vector3();
  7850. const _center = /*@__PURE__*/ new Vector3();
  7851. const _extents = /*@__PURE__*/ new Vector3();
  7852. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7853. const _testAxis = /*@__PURE__*/ new Vector3();
  7854. function satForAxes( axes, v0, v1, v2, extents ) {
  7855. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7856. _testAxis.fromArray( axes, i );
  7857. // project the aabb onto the separating axis
  7858. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7859. // project all 3 vertices of the triangle onto the separating axis
  7860. const p0 = v0.dot( _testAxis );
  7861. const p1 = v1.dot( _testAxis );
  7862. const p2 = v2.dot( _testAxis );
  7863. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7864. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7865. // points of the projected triangle are outside the projected half-length of the aabb
  7866. // the axis is separating and we can exit
  7867. return false;
  7868. }
  7869. }
  7870. return true;
  7871. }
  7872. const _box$3 = /*@__PURE__*/ new Box3();
  7873. const _v1$6 = /*@__PURE__*/ new Vector3();
  7874. const _v2$3 = /*@__PURE__*/ new Vector3();
  7875. /**
  7876. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7877. * used as a Bounding Sphere for 3D objects.
  7878. */
  7879. class Sphere {
  7880. /**
  7881. * Constructs a new sphere.
  7882. *
  7883. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7884. * @param {number} [radius=-1] - The radius of the sphere.
  7885. */
  7886. constructor( center = new Vector3(), radius = -1 ) {
  7887. /**
  7888. * This flag can be used for type testing.
  7889. *
  7890. * @type {boolean}
  7891. * @readonly
  7892. * @default true
  7893. */
  7894. this.isSphere = true;
  7895. /**
  7896. * The center of the sphere
  7897. *
  7898. * @type {Vector3}
  7899. */
  7900. this.center = center;
  7901. /**
  7902. * The radius of the sphere.
  7903. *
  7904. * @type {number}
  7905. */
  7906. this.radius = radius;
  7907. }
  7908. /**
  7909. * Sets the sphere's components by copying the given values.
  7910. *
  7911. * @param {Vector3} center - The center.
  7912. * @param {number} radius - The radius.
  7913. * @return {Sphere} A reference to this sphere.
  7914. */
  7915. set( center, radius ) {
  7916. this.center.copy( center );
  7917. this.radius = radius;
  7918. return this;
  7919. }
  7920. /**
  7921. * Computes the minimum bounding sphere for list of points.
  7922. * If the optional center point is given, it is used as the sphere's
  7923. * center. Otherwise, the center of the axis-aligned bounding box
  7924. * encompassing the points is calculated.
  7925. *
  7926. * @param {Array<Vector3>} points - A list of points in 3D space.
  7927. * @param {Vector3} [optionalCenter] - The center of the sphere.
  7928. * @return {Sphere} A reference to this sphere.
  7929. */
  7930. setFromPoints( points, optionalCenter ) {
  7931. const center = this.center;
  7932. if ( optionalCenter !== undefined ) {
  7933. center.copy( optionalCenter );
  7934. } else {
  7935. _box$3.setFromPoints( points ).getCenter( center );
  7936. }
  7937. let maxRadiusSq = 0;
  7938. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7939. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7940. }
  7941. this.radius = Math.sqrt( maxRadiusSq );
  7942. return this;
  7943. }
  7944. /**
  7945. * Copies the values of the given sphere to this instance.
  7946. *
  7947. * @param {Sphere} sphere - The sphere to copy.
  7948. * @return {Sphere} A reference to this sphere.
  7949. */
  7950. copy( sphere ) {
  7951. this.center.copy( sphere.center );
  7952. this.radius = sphere.radius;
  7953. return this;
  7954. }
  7955. /**
  7956. * Returns `true` if the sphere is empty (the radius set to a negative number).
  7957. *
  7958. * Spheres with a radius of `0` contain only their center point and are not
  7959. * considered to be empty.
  7960. *
  7961. * @return {boolean} Whether this sphere is empty or not.
  7962. */
  7963. isEmpty() {
  7964. return ( this.radius < 0 );
  7965. }
  7966. /**
  7967. * Makes this sphere empty which means in encloses a zero space in 3D.
  7968. *
  7969. * @return {Sphere} A reference to this sphere.
  7970. */
  7971. makeEmpty() {
  7972. this.center.set( 0, 0, 0 );
  7973. this.radius = -1;
  7974. return this;
  7975. }
  7976. /**
  7977. * Returns `true` if this sphere contains the given point inclusive of
  7978. * the surface of the sphere.
  7979. *
  7980. * @param {Vector3} point - The point to check.
  7981. * @return {boolean} Whether this sphere contains the given point or not.
  7982. */
  7983. containsPoint( point ) {
  7984. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7985. }
  7986. /**
  7987. * Returns the closest distance from the boundary of the sphere to the
  7988. * given point. If the sphere contains the point, the distance will
  7989. * be negative.
  7990. *
  7991. * @param {Vector3} point - The point to compute the distance to.
  7992. * @return {number} The distance to the point.
  7993. */
  7994. distanceToPoint( point ) {
  7995. return ( point.distanceTo( this.center ) - this.radius );
  7996. }
  7997. /**
  7998. * Returns `true` if this sphere intersects with the given one.
  7999. *
  8000. * @param {Sphere} sphere - The sphere to test.
  8001. * @return {boolean} Whether this sphere intersects with the given one or not.
  8002. */
  8003. intersectsSphere( sphere ) {
  8004. const radiusSum = this.radius + sphere.radius;
  8005. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8006. }
  8007. /**
  8008. * Returns `true` if this sphere intersects with the given box.
  8009. *
  8010. * @param {Box3} box - The box to test.
  8011. * @return {boolean} Whether this sphere intersects with the given box or not.
  8012. */
  8013. intersectsBox( box ) {
  8014. return box.intersectsSphere( this );
  8015. }
  8016. /**
  8017. * Returns `true` if this sphere intersects with the given plane.
  8018. *
  8019. * @param {Plane} plane - The plane to test.
  8020. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8021. */
  8022. intersectsPlane( plane ) {
  8023. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8024. }
  8025. /**
  8026. * Clamps a point within the sphere. If the point is outside the sphere, it
  8027. * will clamp it to the closest point on the edge of the sphere. Points
  8028. * already inside the sphere will not be affected.
  8029. *
  8030. * @param {Vector3} point - The plane to clamp.
  8031. * @param {Vector3} target - The target vector that is used to store the method's result.
  8032. * @return {Vector3} The clamped point.
  8033. */
  8034. clampPoint( point, target ) {
  8035. const deltaLengthSq = this.center.distanceToSquared( point );
  8036. target.copy( point );
  8037. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8038. target.sub( this.center ).normalize();
  8039. target.multiplyScalar( this.radius ).add( this.center );
  8040. }
  8041. return target;
  8042. }
  8043. /**
  8044. * Returns a bounding box that encloses this sphere.
  8045. *
  8046. * @param {Box3} target - The target box that is used to store the method's result.
  8047. * @return {Box3} The bounding box that encloses this sphere.
  8048. */
  8049. getBoundingBox( target ) {
  8050. if ( this.isEmpty() ) {
  8051. // Empty sphere produces empty bounding box
  8052. target.makeEmpty();
  8053. return target;
  8054. }
  8055. target.set( this.center, this.center );
  8056. target.expandByScalar( this.radius );
  8057. return target;
  8058. }
  8059. /**
  8060. * Transforms this sphere with the given 4x4 transformation matrix.
  8061. *
  8062. * @param {Matrix4} matrix - The transformation matrix.
  8063. * @return {Sphere} A reference to this sphere.
  8064. */
  8065. applyMatrix4( matrix ) {
  8066. this.center.applyMatrix4( matrix );
  8067. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8068. return this;
  8069. }
  8070. /**
  8071. * Translates the sphere's center by the given offset.
  8072. *
  8073. * @param {Vector3} offset - The offset.
  8074. * @return {Sphere} A reference to this sphere.
  8075. */
  8076. translate( offset ) {
  8077. this.center.add( offset );
  8078. return this;
  8079. }
  8080. /**
  8081. * Expands the boundaries of this sphere to include the given point.
  8082. *
  8083. * @param {Vector3} point - The point to include.
  8084. * @return {Sphere} A reference to this sphere.
  8085. */
  8086. expandByPoint( point ) {
  8087. if ( this.isEmpty() ) {
  8088. this.center.copy( point );
  8089. this.radius = 0;
  8090. return this;
  8091. }
  8092. _v1$6.subVectors( point, this.center );
  8093. const lengthSq = _v1$6.lengthSq();
  8094. if ( lengthSq > ( this.radius * this.radius ) ) {
  8095. // calculate the minimal sphere
  8096. const length = Math.sqrt( lengthSq );
  8097. const delta = ( length - this.radius ) * 0.5;
  8098. this.center.addScaledVector( _v1$6, delta / length );
  8099. this.radius += delta;
  8100. }
  8101. return this;
  8102. }
  8103. /**
  8104. * Expands this sphere to enclose both the original sphere and the given sphere.
  8105. *
  8106. * @param {Sphere} sphere - The sphere to include.
  8107. * @return {Sphere} A reference to this sphere.
  8108. */
  8109. union( sphere ) {
  8110. if ( sphere.isEmpty() ) {
  8111. return this;
  8112. }
  8113. if ( this.isEmpty() ) {
  8114. this.copy( sphere );
  8115. return this;
  8116. }
  8117. if ( this.center.equals( sphere.center ) === true ) {
  8118. this.radius = Math.max( this.radius, sphere.radius );
  8119. } else {
  8120. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8121. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8122. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8123. }
  8124. return this;
  8125. }
  8126. /**
  8127. * Returns `true` if this sphere is equal with the given one.
  8128. *
  8129. * @param {Sphere} sphere - The sphere to test for equality.
  8130. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8131. */
  8132. equals( sphere ) {
  8133. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8134. }
  8135. /**
  8136. * Returns a new sphere with copied values from this instance.
  8137. *
  8138. * @return {Sphere} A clone of this instance.
  8139. */
  8140. clone() {
  8141. return new this.constructor().copy( this );
  8142. }
  8143. /**
  8144. * Returns a serialized structure of the bounding sphere.
  8145. *
  8146. * @return {Object} Serialized structure with fields representing the object state.
  8147. */
  8148. toJSON() {
  8149. return {
  8150. radius: this.radius,
  8151. center: this.center.toArray()
  8152. };
  8153. }
  8154. /**
  8155. * Returns a serialized structure of the bounding sphere.
  8156. *
  8157. * @param {Object} json - The serialized json to set the sphere from.
  8158. * @return {Box3} A reference to this bounding sphere.
  8159. */
  8160. fromJSON( json ) {
  8161. this.radius = json.radius;
  8162. this.center.fromArray( json.center );
  8163. return this;
  8164. }
  8165. }
  8166. const _vector$a = /*@__PURE__*/ new Vector3();
  8167. const _segCenter = /*@__PURE__*/ new Vector3();
  8168. const _segDir = /*@__PURE__*/ new Vector3();
  8169. const _diff = /*@__PURE__*/ new Vector3();
  8170. const _edge1 = /*@__PURE__*/ new Vector3();
  8171. const _edge2 = /*@__PURE__*/ new Vector3();
  8172. const _normal$1 = /*@__PURE__*/ new Vector3();
  8173. /**
  8174. * A ray that emits from an origin in a certain direction. The class is used by
  8175. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8176. * mouse picking (working out what objects in the 3D space the mouse is over)
  8177. * amongst other things.
  8178. */
  8179. class Ray {
  8180. /**
  8181. * Constructs a new ray.
  8182. *
  8183. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8184. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8185. */
  8186. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8187. /**
  8188. * The origin of the ray.
  8189. *
  8190. * @type {Vector3}
  8191. */
  8192. this.origin = origin;
  8193. /**
  8194. * The (normalized) direction of the ray.
  8195. *
  8196. * @type {Vector3}
  8197. */
  8198. this.direction = direction;
  8199. }
  8200. /**
  8201. * Sets the ray's components by copying the given values.
  8202. *
  8203. * @param {Vector3} origin - The origin.
  8204. * @param {Vector3} direction - The direction.
  8205. * @return {Ray} A reference to this ray.
  8206. */
  8207. set( origin, direction ) {
  8208. this.origin.copy( origin );
  8209. this.direction.copy( direction );
  8210. return this;
  8211. }
  8212. /**
  8213. * Copies the values of the given ray to this instance.
  8214. *
  8215. * @param {Ray} ray - The ray to copy.
  8216. * @return {Ray} A reference to this ray.
  8217. */
  8218. copy( ray ) {
  8219. this.origin.copy( ray.origin );
  8220. this.direction.copy( ray.direction );
  8221. return this;
  8222. }
  8223. /**
  8224. * Returns a vector that is located at a given distance along this ray.
  8225. *
  8226. * @param {number} t - The distance along the ray to retrieve a position for.
  8227. * @param {Vector3} target - The target vector that is used to store the method's result.
  8228. * @return {Vector3} A position on the ray.
  8229. */
  8230. at( t, target ) {
  8231. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8232. }
  8233. /**
  8234. * Adjusts the direction of the ray to point at the given vector in world space.
  8235. *
  8236. * @param {Vector3} v - The target position.
  8237. * @return {Ray} A reference to this ray.
  8238. */
  8239. lookAt( v ) {
  8240. this.direction.copy( v ).sub( this.origin ).normalize();
  8241. return this;
  8242. }
  8243. /**
  8244. * Shift the origin of this ray along its direction by the given distance.
  8245. *
  8246. * @param {number} t - The distance along the ray to interpolate.
  8247. * @return {Ray} A reference to this ray.
  8248. */
  8249. recast( t ) {
  8250. this.origin.copy( this.at( t, _vector$a ) );
  8251. return this;
  8252. }
  8253. /**
  8254. * Returns the point along this ray that is closest to the given point.
  8255. *
  8256. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8257. * @param {Vector3} target - The target vector that is used to store the method's result.
  8258. * @return {Vector3} The closest point on this ray.
  8259. */
  8260. closestPointToPoint( point, target ) {
  8261. target.subVectors( point, this.origin );
  8262. const directionDistance = target.dot( this.direction );
  8263. if ( directionDistance < 0 ) {
  8264. return target.copy( this.origin );
  8265. }
  8266. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8267. }
  8268. /**
  8269. * Returns the distance of the closest approach between this ray and the given point.
  8270. *
  8271. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8272. * @return {number} The distance.
  8273. */
  8274. distanceToPoint( point ) {
  8275. return Math.sqrt( this.distanceSqToPoint( point ) );
  8276. }
  8277. /**
  8278. * Returns the squared distance of the closest approach between this ray and the given point.
  8279. *
  8280. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8281. * @return {number} The squared distance.
  8282. */
  8283. distanceSqToPoint( point ) {
  8284. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8285. // point behind the ray
  8286. if ( directionDistance < 0 ) {
  8287. return this.origin.distanceToSquared( point );
  8288. }
  8289. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8290. return _vector$a.distanceToSquared( point );
  8291. }
  8292. /**
  8293. * Returns the squared distance between this ray and the given line segment.
  8294. *
  8295. * @param {Vector3} v0 - The start point of the line segment.
  8296. * @param {Vector3} v1 - The end point of the line segment.
  8297. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8298. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8299. * @return {number} The squared distance.
  8300. */
  8301. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8302. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8303. // It returns the min distance between the ray and the segment
  8304. // defined by v0 and v1
  8305. // It can also set two optional targets :
  8306. // - The closest point on the ray
  8307. // - The closest point on the segment
  8308. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8309. _segDir.copy( v1 ).sub( v0 ).normalize();
  8310. _diff.copy( this.origin ).sub( _segCenter );
  8311. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8312. const a01 = - this.direction.dot( _segDir );
  8313. const b0 = _diff.dot( this.direction );
  8314. const b1 = - _diff.dot( _segDir );
  8315. const c = _diff.lengthSq();
  8316. const det = Math.abs( 1 - a01 * a01 );
  8317. let s0, s1, sqrDist, extDet;
  8318. if ( det > 0 ) {
  8319. // The ray and segment are not parallel.
  8320. s0 = a01 * b1 - b0;
  8321. s1 = a01 * b0 - b1;
  8322. extDet = segExtent * det;
  8323. if ( s0 >= 0 ) {
  8324. if ( s1 >= - extDet ) {
  8325. if ( s1 <= extDet ) {
  8326. // region 0
  8327. // Minimum at interior points of ray and segment.
  8328. const invDet = 1 / det;
  8329. s0 *= invDet;
  8330. s1 *= invDet;
  8331. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8332. } else {
  8333. // region 1
  8334. s1 = segExtent;
  8335. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8336. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8337. }
  8338. } else {
  8339. // region 5
  8340. s1 = - segExtent;
  8341. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8342. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8343. }
  8344. } else {
  8345. if ( s1 <= - extDet ) {
  8346. // region 4
  8347. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8348. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8349. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8350. } else if ( s1 <= extDet ) {
  8351. // region 3
  8352. s0 = 0;
  8353. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8354. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8355. } else {
  8356. // region 2
  8357. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8358. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8359. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8360. }
  8361. }
  8362. } else {
  8363. // Ray and segment are parallel.
  8364. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8365. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8366. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8367. }
  8368. if ( optionalPointOnRay ) {
  8369. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8370. }
  8371. if ( optionalPointOnSegment ) {
  8372. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8373. }
  8374. return sqrDist;
  8375. }
  8376. /**
  8377. * Intersects this ray with the given sphere, returning the intersection
  8378. * point or `null` if there is no intersection.
  8379. *
  8380. * @param {Sphere} sphere - The sphere to intersect.
  8381. * @param {Vector3} target - The target vector that is used to store the method's result.
  8382. * @return {?Vector3} The intersection point.
  8383. */
  8384. intersectSphere( sphere, target ) {
  8385. _vector$a.subVectors( sphere.center, this.origin );
  8386. const tca = _vector$a.dot( this.direction );
  8387. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8388. const radius2 = sphere.radius * sphere.radius;
  8389. if ( d2 > radius2 ) return null;
  8390. const thc = Math.sqrt( radius2 - d2 );
  8391. // t0 = first intersect point - entrance on front of sphere
  8392. const t0 = tca - thc;
  8393. // t1 = second intersect point - exit point on back of sphere
  8394. const t1 = tca + thc;
  8395. // test to see if t1 is behind the ray - if so, return null
  8396. if ( t1 < 0 ) return null;
  8397. // test to see if t0 is behind the ray:
  8398. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8399. // in order to always return an intersect point that is in front of the ray.
  8400. if ( t0 < 0 ) return this.at( t1, target );
  8401. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8402. return this.at( t0, target );
  8403. }
  8404. /**
  8405. * Returns `true` if this ray intersects with the given sphere.
  8406. *
  8407. * @param {Sphere} sphere - The sphere to intersect.
  8408. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8409. */
  8410. intersectsSphere( sphere ) {
  8411. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8412. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8413. }
  8414. /**
  8415. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8416. * does not intersect with the plane.
  8417. *
  8418. * @param {Plane} plane - The plane to compute the distance to.
  8419. * @return {?number} Whether this ray intersects with the given sphere or not.
  8420. */
  8421. distanceToPlane( plane ) {
  8422. const denominator = plane.normal.dot( this.direction );
  8423. if ( denominator === 0 ) {
  8424. // line is coplanar, return origin
  8425. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8426. return 0;
  8427. }
  8428. // Null is preferable to undefined since undefined means.... it is undefined
  8429. return null;
  8430. }
  8431. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8432. // Return if the ray never intersects the plane
  8433. return t >= 0 ? t : null;
  8434. }
  8435. /**
  8436. * Intersects this ray with the given plane, returning the intersection
  8437. * point or `null` if there is no intersection.
  8438. *
  8439. * @param {Plane} plane - The plane to intersect.
  8440. * @param {Vector3} target - The target vector that is used to store the method's result.
  8441. * @return {?Vector3} The intersection point.
  8442. */
  8443. intersectPlane( plane, target ) {
  8444. const t = this.distanceToPlane( plane );
  8445. if ( t === null ) {
  8446. return null;
  8447. }
  8448. return this.at( t, target );
  8449. }
  8450. /**
  8451. * Returns `true` if this ray intersects with the given plane.
  8452. *
  8453. * @param {Plane} plane - The plane to intersect.
  8454. * @return {boolean} Whether this ray intersects with the given plane or not.
  8455. */
  8456. intersectsPlane( plane ) {
  8457. // check if the ray lies on the plane first
  8458. const distToPoint = plane.distanceToPoint( this.origin );
  8459. if ( distToPoint === 0 ) {
  8460. return true;
  8461. }
  8462. const denominator = plane.normal.dot( this.direction );
  8463. if ( denominator * distToPoint < 0 ) {
  8464. return true;
  8465. }
  8466. // ray origin is behind the plane (and is pointing behind it)
  8467. return false;
  8468. }
  8469. /**
  8470. * Intersects this ray with the given bounding box, returning the intersection
  8471. * point or `null` if there is no intersection.
  8472. *
  8473. * @param {Box3} box - The box to intersect.
  8474. * @param {Vector3} target - The target vector that is used to store the method's result.
  8475. * @return {?Vector3} The intersection point.
  8476. */
  8477. intersectBox( box, target ) {
  8478. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8479. const invdirx = 1 / this.direction.x,
  8480. invdiry = 1 / this.direction.y,
  8481. invdirz = 1 / this.direction.z;
  8482. const origin = this.origin;
  8483. if ( invdirx >= 0 ) {
  8484. tmin = ( box.min.x - origin.x ) * invdirx;
  8485. tmax = ( box.max.x - origin.x ) * invdirx;
  8486. } else {
  8487. tmin = ( box.max.x - origin.x ) * invdirx;
  8488. tmax = ( box.min.x - origin.x ) * invdirx;
  8489. }
  8490. if ( invdiry >= 0 ) {
  8491. tymin = ( box.min.y - origin.y ) * invdiry;
  8492. tymax = ( box.max.y - origin.y ) * invdiry;
  8493. } else {
  8494. tymin = ( box.max.y - origin.y ) * invdiry;
  8495. tymax = ( box.min.y - origin.y ) * invdiry;
  8496. }
  8497. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8498. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8499. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8500. if ( invdirz >= 0 ) {
  8501. tzmin = ( box.min.z - origin.z ) * invdirz;
  8502. tzmax = ( box.max.z - origin.z ) * invdirz;
  8503. } else {
  8504. tzmin = ( box.max.z - origin.z ) * invdirz;
  8505. tzmax = ( box.min.z - origin.z ) * invdirz;
  8506. }
  8507. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8508. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8509. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8510. //return point closest to the ray (positive side)
  8511. if ( tmax < 0 ) return null;
  8512. return this.at( tmin >= 0 ? tmin : tmax, target );
  8513. }
  8514. /**
  8515. * Returns `true` if this ray intersects with the given box.
  8516. *
  8517. * @param {Box3} box - The box to intersect.
  8518. * @return {boolean} Whether this ray intersects with the given box or not.
  8519. */
  8520. intersectsBox( box ) {
  8521. return this.intersectBox( box, _vector$a ) !== null;
  8522. }
  8523. /**
  8524. * Intersects this ray with the given triangle, returning the intersection
  8525. * point or `null` if there is no intersection.
  8526. *
  8527. * @param {Vector3} a - The first vertex of the triangle.
  8528. * @param {Vector3} b - The second vertex of the triangle.
  8529. * @param {Vector3} c - The third vertex of the triangle.
  8530. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8531. * @param {Vector3} target - The target vector that is used to store the method's result.
  8532. * @return {?Vector3} The intersection point.
  8533. */
  8534. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8535. // Compute the offset origin, edges, and normal.
  8536. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8537. _edge1.subVectors( b, a );
  8538. _edge2.subVectors( c, a );
  8539. _normal$1.crossVectors( _edge1, _edge2 );
  8540. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8541. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8542. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8543. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8544. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8545. let DdN = this.direction.dot( _normal$1 );
  8546. let sign;
  8547. if ( DdN > 0 ) {
  8548. if ( backfaceCulling ) return null;
  8549. sign = 1;
  8550. } else if ( DdN < 0 ) {
  8551. sign = -1;
  8552. DdN = - DdN;
  8553. } else {
  8554. return null;
  8555. }
  8556. _diff.subVectors( this.origin, a );
  8557. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8558. // b1 < 0, no intersection
  8559. if ( DdQxE2 < 0 ) {
  8560. return null;
  8561. }
  8562. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8563. // b2 < 0, no intersection
  8564. if ( DdE1xQ < 0 ) {
  8565. return null;
  8566. }
  8567. // b1+b2 > 1, no intersection
  8568. if ( DdQxE2 + DdE1xQ > DdN ) {
  8569. return null;
  8570. }
  8571. // Line intersects triangle, check if ray does.
  8572. const QdN = - sign * _diff.dot( _normal$1 );
  8573. // t < 0, no intersection
  8574. if ( QdN < 0 ) {
  8575. return null;
  8576. }
  8577. // Ray intersects triangle.
  8578. return this.at( QdN / DdN, target );
  8579. }
  8580. /**
  8581. * Transforms this ray with the given 4x4 transformation matrix.
  8582. *
  8583. * @param {Matrix4} matrix4 - The transformation matrix.
  8584. * @return {Ray} A reference to this ray.
  8585. */
  8586. applyMatrix4( matrix4 ) {
  8587. this.origin.applyMatrix4( matrix4 );
  8588. this.direction.transformDirection( matrix4 );
  8589. return this;
  8590. }
  8591. /**
  8592. * Returns `true` if this ray is equal with the given one.
  8593. *
  8594. * @param {Ray} ray - The ray to test for equality.
  8595. * @return {boolean} Whether this ray is equal with the given one.
  8596. */
  8597. equals( ray ) {
  8598. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8599. }
  8600. /**
  8601. * Returns a new ray with copied values from this instance.
  8602. *
  8603. * @return {Ray} A clone of this instance.
  8604. */
  8605. clone() {
  8606. return new this.constructor().copy( this );
  8607. }
  8608. }
  8609. /**
  8610. * Represents a 4x4 matrix.
  8611. *
  8612. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8613. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial]{@link https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices}
  8614. *
  8615. * This allows a 3D vector representing a point in 3D space to undergo
  8616. * transformations such as translation, rotation, shear, scale, reflection,
  8617. * orthogonal or perspective projection and so on, by being multiplied by the
  8618. * matrix. This is known as `applying` the matrix to the vector.
  8619. *
  8620. * A Note on Row-Major and Column-Major Ordering:
  8621. *
  8622. * The constructor and {@link Matrix3#set} method take arguments in
  8623. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  8624. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8625. * This means that calling:
  8626. * ```js
  8627. * const m = new THREE.Matrix4();
  8628. * m.set( 11, 12, 13, 14,
  8629. * 21, 22, 23, 24,
  8630. * 31, 32, 33, 34,
  8631. * 41, 42, 43, 44 );
  8632. * ```
  8633. * will result in the elements array containing:
  8634. * ```js
  8635. * m.elements = [ 11, 21, 31, 41,
  8636. * 12, 22, 32, 42,
  8637. * 13, 23, 33, 43,
  8638. * 14, 24, 34, 44 ];
  8639. * ```
  8640. * and internally all calculations are performed using column-major ordering.
  8641. * However, as the actual ordering makes no difference mathematically and
  8642. * most people are used to thinking about matrices in row-major order, the
  8643. * three.js documentation shows matrices in row-major order. Just bear in
  8644. * mind that if you are reading the source code, you'll have to take the
  8645. * transpose of any matrices outlined here to make sense of the calculations.
  8646. */
  8647. class Matrix4 {
  8648. /**
  8649. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8650. * in row-major order. If no arguments are provided, the constructor
  8651. * initializes the matrix as an identity matrix.
  8652. *
  8653. * @param {number} [n11] - 1-1 matrix element.
  8654. * @param {number} [n12] - 1-2 matrix element.
  8655. * @param {number} [n13] - 1-3 matrix element.
  8656. * @param {number} [n14] - 1-4 matrix element.
  8657. * @param {number} [n21] - 2-1 matrix element.
  8658. * @param {number} [n22] - 2-2 matrix element.
  8659. * @param {number} [n23] - 2-3 matrix element.
  8660. * @param {number} [n24] - 2-4 matrix element.
  8661. * @param {number} [n31] - 3-1 matrix element.
  8662. * @param {number} [n32] - 3-2 matrix element.
  8663. * @param {number} [n33] - 3-3 matrix element.
  8664. * @param {number} [n34] - 3-4 matrix element.
  8665. * @param {number} [n41] - 4-1 matrix element.
  8666. * @param {number} [n42] - 4-2 matrix element.
  8667. * @param {number} [n43] - 4-3 matrix element.
  8668. * @param {number} [n44] - 4-4 matrix element.
  8669. */
  8670. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8671. /**
  8672. * This flag can be used for type testing.
  8673. *
  8674. * @type {boolean}
  8675. * @readonly
  8676. * @default true
  8677. */
  8678. Matrix4.prototype.isMatrix4 = true;
  8679. /**
  8680. * A column-major list of matrix values.
  8681. *
  8682. * @type {Array<number>}
  8683. */
  8684. this.elements = [
  8685. 1, 0, 0, 0,
  8686. 0, 1, 0, 0,
  8687. 0, 0, 1, 0,
  8688. 0, 0, 0, 1
  8689. ];
  8690. if ( n11 !== undefined ) {
  8691. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8692. }
  8693. }
  8694. /**
  8695. * Sets the elements of the matrix.The arguments are supposed to be
  8696. * in row-major order.
  8697. *
  8698. * @param {number} [n11] - 1-1 matrix element.
  8699. * @param {number} [n12] - 1-2 matrix element.
  8700. * @param {number} [n13] - 1-3 matrix element.
  8701. * @param {number} [n14] - 1-4 matrix element.
  8702. * @param {number} [n21] - 2-1 matrix element.
  8703. * @param {number} [n22] - 2-2 matrix element.
  8704. * @param {number} [n23] - 2-3 matrix element.
  8705. * @param {number} [n24] - 2-4 matrix element.
  8706. * @param {number} [n31] - 3-1 matrix element.
  8707. * @param {number} [n32] - 3-2 matrix element.
  8708. * @param {number} [n33] - 3-3 matrix element.
  8709. * @param {number} [n34] - 3-4 matrix element.
  8710. * @param {number} [n41] - 4-1 matrix element.
  8711. * @param {number} [n42] - 4-2 matrix element.
  8712. * @param {number} [n43] - 4-3 matrix element.
  8713. * @param {number} [n44] - 4-4 matrix element.
  8714. * @return {Matrix4} A reference to this matrix.
  8715. */
  8716. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8717. const te = this.elements;
  8718. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8719. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8720. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8721. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8722. return this;
  8723. }
  8724. /**
  8725. * Sets this matrix to the 4x4 identity matrix.
  8726. *
  8727. * @return {Matrix4} A reference to this matrix.
  8728. */
  8729. identity() {
  8730. this.set(
  8731. 1, 0, 0, 0,
  8732. 0, 1, 0, 0,
  8733. 0, 0, 1, 0,
  8734. 0, 0, 0, 1
  8735. );
  8736. return this;
  8737. }
  8738. /**
  8739. * Returns a matrix with copied values from this instance.
  8740. *
  8741. * @return {Matrix4} A clone of this instance.
  8742. */
  8743. clone() {
  8744. return new Matrix4().fromArray( this.elements );
  8745. }
  8746. /**
  8747. * Copies the values of the given matrix to this instance.
  8748. *
  8749. * @param {Matrix4} m - The matrix to copy.
  8750. * @return {Matrix4} A reference to this matrix.
  8751. */
  8752. copy( m ) {
  8753. const te = this.elements;
  8754. const me = m.elements;
  8755. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8756. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8757. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8758. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8759. return this;
  8760. }
  8761. /**
  8762. * Copies the translation component of the given matrix
  8763. * into this matrix's translation component.
  8764. *
  8765. * @param {Matrix4} m - The matrix to copy the translation component.
  8766. * @return {Matrix4} A reference to this matrix.
  8767. */
  8768. copyPosition( m ) {
  8769. const te = this.elements, me = m.elements;
  8770. te[ 12 ] = me[ 12 ];
  8771. te[ 13 ] = me[ 13 ];
  8772. te[ 14 ] = me[ 14 ];
  8773. return this;
  8774. }
  8775. /**
  8776. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8777. *
  8778. * @param {Matrix3} m - The 3x3 matrix.
  8779. * @return {Matrix4} A reference to this matrix.
  8780. */
  8781. setFromMatrix3( m ) {
  8782. const me = m.elements;
  8783. this.set(
  8784. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8785. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8786. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8787. 0, 0, 0, 1
  8788. );
  8789. return this;
  8790. }
  8791. /**
  8792. * Extracts the basis of this matrix into the three axis vectors provided.
  8793. *
  8794. * @param {Vector3} xAxis - The basis's x axis.
  8795. * @param {Vector3} yAxis - The basis's y axis.
  8796. * @param {Vector3} zAxis - The basis's z axis.
  8797. * @return {Matrix4} A reference to this matrix.
  8798. */
  8799. extractBasis( xAxis, yAxis, zAxis ) {
  8800. xAxis.setFromMatrixColumn( this, 0 );
  8801. yAxis.setFromMatrixColumn( this, 1 );
  8802. zAxis.setFromMatrixColumn( this, 2 );
  8803. return this;
  8804. }
  8805. /**
  8806. * Sets the given basis vectors to this matrix.
  8807. *
  8808. * @param {Vector3} xAxis - The basis's x axis.
  8809. * @param {Vector3} yAxis - The basis's y axis.
  8810. * @param {Vector3} zAxis - The basis's z axis.
  8811. * @return {Matrix4} A reference to this matrix.
  8812. */
  8813. makeBasis( xAxis, yAxis, zAxis ) {
  8814. this.set(
  8815. xAxis.x, yAxis.x, zAxis.x, 0,
  8816. xAxis.y, yAxis.y, zAxis.y, 0,
  8817. xAxis.z, yAxis.z, zAxis.z, 0,
  8818. 0, 0, 0, 1
  8819. );
  8820. return this;
  8821. }
  8822. /**
  8823. * Extracts the rotation component of the given matrix
  8824. * into this matrix's rotation component.
  8825. *
  8826. * Note: This method does not support reflection matrices.
  8827. *
  8828. * @param {Matrix4} m - The matrix.
  8829. * @return {Matrix4} A reference to this matrix.
  8830. */
  8831. extractRotation( m ) {
  8832. const te = this.elements;
  8833. const me = m.elements;
  8834. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8835. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8836. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8837. te[ 0 ] = me[ 0 ] * scaleX;
  8838. te[ 1 ] = me[ 1 ] * scaleX;
  8839. te[ 2 ] = me[ 2 ] * scaleX;
  8840. te[ 3 ] = 0;
  8841. te[ 4 ] = me[ 4 ] * scaleY;
  8842. te[ 5 ] = me[ 5 ] * scaleY;
  8843. te[ 6 ] = me[ 6 ] * scaleY;
  8844. te[ 7 ] = 0;
  8845. te[ 8 ] = me[ 8 ] * scaleZ;
  8846. te[ 9 ] = me[ 9 ] * scaleZ;
  8847. te[ 10 ] = me[ 10 ] * scaleZ;
  8848. te[ 11 ] = 0;
  8849. te[ 12 ] = 0;
  8850. te[ 13 ] = 0;
  8851. te[ 14 ] = 0;
  8852. te[ 15 ] = 1;
  8853. return this;
  8854. }
  8855. /**
  8856. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8857. * the rotation specified by the given Euler angles. The rest of
  8858. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8859. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  8860. * for a complete list.
  8861. *
  8862. * @param {Euler} euler - The Euler angles.
  8863. * @return {Matrix4} A reference to this matrix.
  8864. */
  8865. makeRotationFromEuler( euler ) {
  8866. const te = this.elements;
  8867. const x = euler.x, y = euler.y, z = euler.z;
  8868. const a = Math.cos( x ), b = Math.sin( x );
  8869. const c = Math.cos( y ), d = Math.sin( y );
  8870. const e = Math.cos( z ), f = Math.sin( z );
  8871. if ( euler.order === 'XYZ' ) {
  8872. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8873. te[ 0 ] = c * e;
  8874. te[ 4 ] = - c * f;
  8875. te[ 8 ] = d;
  8876. te[ 1 ] = af + be * d;
  8877. te[ 5 ] = ae - bf * d;
  8878. te[ 9 ] = - b * c;
  8879. te[ 2 ] = bf - ae * d;
  8880. te[ 6 ] = be + af * d;
  8881. te[ 10 ] = a * c;
  8882. } else if ( euler.order === 'YXZ' ) {
  8883. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8884. te[ 0 ] = ce + df * b;
  8885. te[ 4 ] = de * b - cf;
  8886. te[ 8 ] = a * d;
  8887. te[ 1 ] = a * f;
  8888. te[ 5 ] = a * e;
  8889. te[ 9 ] = - b;
  8890. te[ 2 ] = cf * b - de;
  8891. te[ 6 ] = df + ce * b;
  8892. te[ 10 ] = a * c;
  8893. } else if ( euler.order === 'ZXY' ) {
  8894. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8895. te[ 0 ] = ce - df * b;
  8896. te[ 4 ] = - a * f;
  8897. te[ 8 ] = de + cf * b;
  8898. te[ 1 ] = cf + de * b;
  8899. te[ 5 ] = a * e;
  8900. te[ 9 ] = df - ce * b;
  8901. te[ 2 ] = - a * d;
  8902. te[ 6 ] = b;
  8903. te[ 10 ] = a * c;
  8904. } else if ( euler.order === 'ZYX' ) {
  8905. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8906. te[ 0 ] = c * e;
  8907. te[ 4 ] = be * d - af;
  8908. te[ 8 ] = ae * d + bf;
  8909. te[ 1 ] = c * f;
  8910. te[ 5 ] = bf * d + ae;
  8911. te[ 9 ] = af * d - be;
  8912. te[ 2 ] = - d;
  8913. te[ 6 ] = b * c;
  8914. te[ 10 ] = a * c;
  8915. } else if ( euler.order === 'YZX' ) {
  8916. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8917. te[ 0 ] = c * e;
  8918. te[ 4 ] = bd - ac * f;
  8919. te[ 8 ] = bc * f + ad;
  8920. te[ 1 ] = f;
  8921. te[ 5 ] = a * e;
  8922. te[ 9 ] = - b * e;
  8923. te[ 2 ] = - d * e;
  8924. te[ 6 ] = ad * f + bc;
  8925. te[ 10 ] = ac - bd * f;
  8926. } else if ( euler.order === 'XZY' ) {
  8927. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8928. te[ 0 ] = c * e;
  8929. te[ 4 ] = - f;
  8930. te[ 8 ] = d * e;
  8931. te[ 1 ] = ac * f + bd;
  8932. te[ 5 ] = a * e;
  8933. te[ 9 ] = ad * f - bc;
  8934. te[ 2 ] = bc * f - ad;
  8935. te[ 6 ] = b * e;
  8936. te[ 10 ] = bd * f + ac;
  8937. }
  8938. // bottom row
  8939. te[ 3 ] = 0;
  8940. te[ 7 ] = 0;
  8941. te[ 11 ] = 0;
  8942. // last column
  8943. te[ 12 ] = 0;
  8944. te[ 13 ] = 0;
  8945. te[ 14 ] = 0;
  8946. te[ 15 ] = 1;
  8947. return this;
  8948. }
  8949. /**
  8950. * Sets the rotation component of this matrix to the rotation specified by
  8951. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  8952. * The rest of the matrix is set to the identity.
  8953. *
  8954. * @param {Quaternion} q - The Quaternion.
  8955. * @return {Matrix4} A reference to this matrix.
  8956. */
  8957. makeRotationFromQuaternion( q ) {
  8958. return this.compose( _zero, q, _one );
  8959. }
  8960. /**
  8961. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  8962. * `target`, and oriented by the up-direction.
  8963. *
  8964. * @param {Vector3} eye - The eye vector.
  8965. * @param {Vector3} target - The target vector.
  8966. * @param {Vector3} up - The up vector.
  8967. * @return {Matrix4} A reference to this matrix.
  8968. */
  8969. lookAt( eye, target, up ) {
  8970. const te = this.elements;
  8971. _z.subVectors( eye, target );
  8972. if ( _z.lengthSq() === 0 ) {
  8973. // eye and target are in the same position
  8974. _z.z = 1;
  8975. }
  8976. _z.normalize();
  8977. _x.crossVectors( up, _z );
  8978. if ( _x.lengthSq() === 0 ) {
  8979. // up and z are parallel
  8980. if ( Math.abs( up.z ) === 1 ) {
  8981. _z.x += 0.0001;
  8982. } else {
  8983. _z.z += 0.0001;
  8984. }
  8985. _z.normalize();
  8986. _x.crossVectors( up, _z );
  8987. }
  8988. _x.normalize();
  8989. _y.crossVectors( _z, _x );
  8990. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8991. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8992. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8993. return this;
  8994. }
  8995. /**
  8996. * Post-multiplies this matrix by the given 4x4 matrix.
  8997. *
  8998. * @param {Matrix4} m - The matrix to multiply with.
  8999. * @return {Matrix4} A reference to this matrix.
  9000. */
  9001. multiply( m ) {
  9002. return this.multiplyMatrices( this, m );
  9003. }
  9004. /**
  9005. * Pre-multiplies this matrix by the given 4x4 matrix.
  9006. *
  9007. * @param {Matrix4} m - The matrix to multiply with.
  9008. * @return {Matrix4} A reference to this matrix.
  9009. */
  9010. premultiply( m ) {
  9011. return this.multiplyMatrices( m, this );
  9012. }
  9013. /**
  9014. * Multiples the given 4x4 matrices and stores the result
  9015. * in this matrix.
  9016. *
  9017. * @param {Matrix4} a - The first matrix.
  9018. * @param {Matrix4} b - The second matrix.
  9019. * @return {Matrix4} A reference to this matrix.
  9020. */
  9021. multiplyMatrices( a, b ) {
  9022. const ae = a.elements;
  9023. const be = b.elements;
  9024. const te = this.elements;
  9025. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9026. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9027. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9028. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9029. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9030. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9031. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9032. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9033. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9034. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9035. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9036. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9037. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9038. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9039. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9040. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9041. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9042. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9043. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9044. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9045. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9046. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9047. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9048. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9049. return this;
  9050. }
  9051. /**
  9052. * Multiplies every component of the matrix by the given scalar.
  9053. *
  9054. * @param {number} s - The scalar.
  9055. * @return {Matrix4} A reference to this matrix.
  9056. */
  9057. multiplyScalar( s ) {
  9058. const te = this.elements;
  9059. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9060. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9061. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9062. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9063. return this;
  9064. }
  9065. /**
  9066. * Computes and returns the determinant of this matrix.
  9067. *
  9068. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  9069. *
  9070. * @return {number} The determinant.
  9071. */
  9072. determinant() {
  9073. const te = this.elements;
  9074. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9075. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9076. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9077. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9078. //TODO: make this more efficient
  9079. return (
  9080. n41 * (
  9081. + n14 * n23 * n32
  9082. - n13 * n24 * n32
  9083. - n14 * n22 * n33
  9084. + n12 * n24 * n33
  9085. + n13 * n22 * n34
  9086. - n12 * n23 * n34
  9087. ) +
  9088. n42 * (
  9089. + n11 * n23 * n34
  9090. - n11 * n24 * n33
  9091. + n14 * n21 * n33
  9092. - n13 * n21 * n34
  9093. + n13 * n24 * n31
  9094. - n14 * n23 * n31
  9095. ) +
  9096. n43 * (
  9097. + n11 * n24 * n32
  9098. - n11 * n22 * n34
  9099. - n14 * n21 * n32
  9100. + n12 * n21 * n34
  9101. + n14 * n22 * n31
  9102. - n12 * n24 * n31
  9103. ) +
  9104. n44 * (
  9105. - n13 * n22 * n31
  9106. - n11 * n23 * n32
  9107. + n11 * n22 * n33
  9108. + n13 * n21 * n32
  9109. - n12 * n21 * n33
  9110. + n12 * n23 * n31
  9111. )
  9112. );
  9113. }
  9114. /**
  9115. * Transposes this matrix in place.
  9116. *
  9117. * @return {Matrix4} A reference to this matrix.
  9118. */
  9119. transpose() {
  9120. const te = this.elements;
  9121. let tmp;
  9122. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9123. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9124. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9125. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9126. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9127. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9128. return this;
  9129. }
  9130. /**
  9131. * Sets the position component for this matrix from the given vector,
  9132. * without affecting the rest of the matrix.
  9133. *
  9134. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9135. * @param {number} y - The y component of the vector.
  9136. * @param {number} z - The z component of the vector.
  9137. * @return {Matrix4} A reference to this matrix.
  9138. */
  9139. setPosition( x, y, z ) {
  9140. const te = this.elements;
  9141. if ( x.isVector3 ) {
  9142. te[ 12 ] = x.x;
  9143. te[ 13 ] = x.y;
  9144. te[ 14 ] = x.z;
  9145. } else {
  9146. te[ 12 ] = x;
  9147. te[ 13 ] = y;
  9148. te[ 14 ] = z;
  9149. }
  9150. return this;
  9151. }
  9152. /**
  9153. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  9154. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9155. * a zero matrix instead.
  9156. *
  9157. * @return {Matrix4} A reference to this matrix.
  9158. */
  9159. invert() {
  9160. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9161. const te = this.elements,
  9162. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9163. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9164. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9165. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9166. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9167. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9168. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9169. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9170. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9171. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9172. const detInv = 1 / det;
  9173. te[ 0 ] = t11 * detInv;
  9174. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9175. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9176. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9177. te[ 4 ] = t12 * detInv;
  9178. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9179. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9180. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9181. te[ 8 ] = t13 * detInv;
  9182. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9183. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9184. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9185. te[ 12 ] = t14 * detInv;
  9186. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9187. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9188. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9189. return this;
  9190. }
  9191. /**
  9192. * Multiplies the columns of this matrix by the given vector.
  9193. *
  9194. * @param {Vector3} v - The scale vector.
  9195. * @return {Matrix4} A reference to this matrix.
  9196. */
  9197. scale( v ) {
  9198. const te = this.elements;
  9199. const x = v.x, y = v.y, z = v.z;
  9200. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9201. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9202. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9203. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9204. return this;
  9205. }
  9206. /**
  9207. * Gets the maximum scale value of the three axes.
  9208. *
  9209. * @return {number} The maximum scale.
  9210. */
  9211. getMaxScaleOnAxis() {
  9212. const te = this.elements;
  9213. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9214. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9215. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9216. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9217. }
  9218. /**
  9219. * Sets this matrix as a translation transform from the given vector.
  9220. *
  9221. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9222. * @param {number} y - The amount to translate in the Y axis.
  9223. * @param {number} z - The amount to translate in the z axis.
  9224. * @return {Matrix4} A reference to this matrix.
  9225. */
  9226. makeTranslation( x, y, z ) {
  9227. if ( x.isVector3 ) {
  9228. this.set(
  9229. 1, 0, 0, x.x,
  9230. 0, 1, 0, x.y,
  9231. 0, 0, 1, x.z,
  9232. 0, 0, 0, 1
  9233. );
  9234. } else {
  9235. this.set(
  9236. 1, 0, 0, x,
  9237. 0, 1, 0, y,
  9238. 0, 0, 1, z,
  9239. 0, 0, 0, 1
  9240. );
  9241. }
  9242. return this;
  9243. }
  9244. /**
  9245. * Sets this matrix as a rotational transformation around the X axis by
  9246. * the given angle.
  9247. *
  9248. * @param {number} theta - The rotation in radians.
  9249. * @return {Matrix4} A reference to this matrix.
  9250. */
  9251. makeRotationX( theta ) {
  9252. const c = Math.cos( theta ), s = Math.sin( theta );
  9253. this.set(
  9254. 1, 0, 0, 0,
  9255. 0, c, - s, 0,
  9256. 0, s, c, 0,
  9257. 0, 0, 0, 1
  9258. );
  9259. return this;
  9260. }
  9261. /**
  9262. * Sets this matrix as a rotational transformation around the Y axis by
  9263. * the given angle.
  9264. *
  9265. * @param {number} theta - The rotation in radians.
  9266. * @return {Matrix4} A reference to this matrix.
  9267. */
  9268. makeRotationY( theta ) {
  9269. const c = Math.cos( theta ), s = Math.sin( theta );
  9270. this.set(
  9271. c, 0, s, 0,
  9272. 0, 1, 0, 0,
  9273. - s, 0, c, 0,
  9274. 0, 0, 0, 1
  9275. );
  9276. return this;
  9277. }
  9278. /**
  9279. * Sets this matrix as a rotational transformation around the Z axis by
  9280. * the given angle.
  9281. *
  9282. * @param {number} theta - The rotation in radians.
  9283. * @return {Matrix4} A reference to this matrix.
  9284. */
  9285. makeRotationZ( theta ) {
  9286. const c = Math.cos( theta ), s = Math.sin( theta );
  9287. this.set(
  9288. c, - s, 0, 0,
  9289. s, c, 0, 0,
  9290. 0, 0, 1, 0,
  9291. 0, 0, 0, 1
  9292. );
  9293. return this;
  9294. }
  9295. /**
  9296. * Sets this matrix as a rotational transformation around the given axis by
  9297. * the given angle.
  9298. *
  9299. * This is a somewhat controversial but mathematically sound alternative to
  9300. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  9301. *
  9302. * @param {Vector3} axis - The normalized rotation axis.
  9303. * @param {number} angle - The rotation in radians.
  9304. * @return {Matrix4} A reference to this matrix.
  9305. */
  9306. makeRotationAxis( axis, angle ) {
  9307. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9308. const c = Math.cos( angle );
  9309. const s = Math.sin( angle );
  9310. const t = 1 - c;
  9311. const x = axis.x, y = axis.y, z = axis.z;
  9312. const tx = t * x, ty = t * y;
  9313. this.set(
  9314. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9315. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9316. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9317. 0, 0, 0, 1
  9318. );
  9319. return this;
  9320. }
  9321. /**
  9322. * Sets this matrix as a scale transformation.
  9323. *
  9324. * @param {number} x - The amount to scale in the X axis.
  9325. * @param {number} y - The amount to scale in the Y axis.
  9326. * @param {number} z - The amount to scale in the Z axis.
  9327. * @return {Matrix4} A reference to this matrix.
  9328. */
  9329. makeScale( x, y, z ) {
  9330. this.set(
  9331. x, 0, 0, 0,
  9332. 0, y, 0, 0,
  9333. 0, 0, z, 0,
  9334. 0, 0, 0, 1
  9335. );
  9336. return this;
  9337. }
  9338. /**
  9339. * Sets this matrix as a shear transformation.
  9340. *
  9341. * @param {number} xy - The amount to shear X by Y.
  9342. * @param {number} xz - The amount to shear X by Z.
  9343. * @param {number} yx - The amount to shear Y by X.
  9344. * @param {number} yz - The amount to shear Y by Z.
  9345. * @param {number} zx - The amount to shear Z by X.
  9346. * @param {number} zy - The amount to shear Z by Y.
  9347. * @return {Matrix4} A reference to this matrix.
  9348. */
  9349. makeShear( xy, xz, yx, yz, zx, zy ) {
  9350. this.set(
  9351. 1, yx, zx, 0,
  9352. xy, 1, zy, 0,
  9353. xz, yz, 1, 0,
  9354. 0, 0, 0, 1
  9355. );
  9356. return this;
  9357. }
  9358. /**
  9359. * Sets this matrix to the transformation composed of the given position,
  9360. * rotation (Quaternion) and scale.
  9361. *
  9362. * @param {Vector3} position - The position vector.
  9363. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9364. * @param {Vector3} scale - The scale vector.
  9365. * @return {Matrix4} A reference to this matrix.
  9366. */
  9367. compose( position, quaternion, scale ) {
  9368. const te = this.elements;
  9369. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9370. const x2 = x + x, y2 = y + y, z2 = z + z;
  9371. const xx = x * x2, xy = x * y2, xz = x * z2;
  9372. const yy = y * y2, yz = y * z2, zz = z * z2;
  9373. const wx = w * x2, wy = w * y2, wz = w * z2;
  9374. const sx = scale.x, sy = scale.y, sz = scale.z;
  9375. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9376. te[ 1 ] = ( xy + wz ) * sx;
  9377. te[ 2 ] = ( xz - wy ) * sx;
  9378. te[ 3 ] = 0;
  9379. te[ 4 ] = ( xy - wz ) * sy;
  9380. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9381. te[ 6 ] = ( yz + wx ) * sy;
  9382. te[ 7 ] = 0;
  9383. te[ 8 ] = ( xz + wy ) * sz;
  9384. te[ 9 ] = ( yz - wx ) * sz;
  9385. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9386. te[ 11 ] = 0;
  9387. te[ 12 ] = position.x;
  9388. te[ 13 ] = position.y;
  9389. te[ 14 ] = position.z;
  9390. te[ 15 ] = 1;
  9391. return this;
  9392. }
  9393. /**
  9394. * Decomposes this matrix into its position, rotation and scale components
  9395. * and provides the result in the given objects.
  9396. *
  9397. * Note: Not all matrices are decomposable in this way. For example, if an
  9398. * object has a non-uniformly scaled parent, then the object's world matrix
  9399. * may not be decomposable, and this method may not be appropriate.
  9400. *
  9401. * @param {Vector3} position - The position vector.
  9402. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9403. * @param {Vector3} scale - The scale vector.
  9404. * @return {Matrix4} A reference to this matrix.
  9405. */
  9406. decompose( position, quaternion, scale ) {
  9407. const te = this.elements;
  9408. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9409. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9410. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9411. // if determine is negative, we need to invert one scale
  9412. const det = this.determinant();
  9413. if ( det < 0 ) sx = - sx;
  9414. position.x = te[ 12 ];
  9415. position.y = te[ 13 ];
  9416. position.z = te[ 14 ];
  9417. // scale the rotation part
  9418. _m1$2.copy( this );
  9419. const invSX = 1 / sx;
  9420. const invSY = 1 / sy;
  9421. const invSZ = 1 / sz;
  9422. _m1$2.elements[ 0 ] *= invSX;
  9423. _m1$2.elements[ 1 ] *= invSX;
  9424. _m1$2.elements[ 2 ] *= invSX;
  9425. _m1$2.elements[ 4 ] *= invSY;
  9426. _m1$2.elements[ 5 ] *= invSY;
  9427. _m1$2.elements[ 6 ] *= invSY;
  9428. _m1$2.elements[ 8 ] *= invSZ;
  9429. _m1$2.elements[ 9 ] *= invSZ;
  9430. _m1$2.elements[ 10 ] *= invSZ;
  9431. quaternion.setFromRotationMatrix( _m1$2 );
  9432. scale.x = sx;
  9433. scale.y = sy;
  9434. scale.z = sz;
  9435. return this;
  9436. }
  9437. /**
  9438. * Creates a perspective projection matrix. This is used internally by
  9439. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9440. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9441. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9442. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9443. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9444. * @param {number} near - The distance from the camera to the near plane.
  9445. * @param {number} far - The distance from the camera to the far plane.
  9446. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9447. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9448. * @return {Matrix4} A reference to this matrix.
  9449. */
  9450. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9451. const te = this.elements;
  9452. const x = 2 * near / ( right - left );
  9453. const y = 2 * near / ( top - bottom );
  9454. const a = ( right + left ) / ( right - left );
  9455. const b = ( top + bottom ) / ( top - bottom );
  9456. let c, d;
  9457. if ( reversedDepth ) {
  9458. c = near / ( far - near );
  9459. d = ( far * near ) / ( far - near );
  9460. } else {
  9461. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9462. c = - ( far + near ) / ( far - near );
  9463. d = ( -2 * far * near ) / ( far - near );
  9464. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9465. c = - far / ( far - near );
  9466. d = ( - far * near ) / ( far - near );
  9467. } else {
  9468. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9469. }
  9470. }
  9471. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9472. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9473. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9474. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9475. return this;
  9476. }
  9477. /**
  9478. * Creates a orthographic projection matrix. This is used internally by
  9479. * {@link OrthographicCamera#updateProjectionMatrix}.
  9480. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9481. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9482. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9483. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9484. * @param {number} near - The distance from the camera to the near plane.
  9485. * @param {number} far - The distance from the camera to the far plane.
  9486. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9487. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9488. * @return {Matrix4} A reference to this matrix.
  9489. */
  9490. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9491. const te = this.elements;
  9492. const x = 2 / ( right - left );
  9493. const y = 2 / ( top - bottom );
  9494. const a = - ( right + left ) / ( right - left );
  9495. const b = - ( top + bottom ) / ( top - bottom );
  9496. let c, d;
  9497. if ( reversedDepth ) {
  9498. c = 1 / ( far - near );
  9499. d = far / ( far - near );
  9500. } else {
  9501. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9502. c = -2 / ( far - near );
  9503. d = - ( far + near ) / ( far - near );
  9504. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9505. c = -1 / ( far - near );
  9506. d = - near / ( far - near );
  9507. } else {
  9508. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9509. }
  9510. }
  9511. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9512. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9513. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9514. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9515. return this;
  9516. }
  9517. /**
  9518. * Returns `true` if this matrix is equal with the given one.
  9519. *
  9520. * @param {Matrix4} matrix - The matrix to test for equality.
  9521. * @return {boolean} Whether this matrix is equal with the given one.
  9522. */
  9523. equals( matrix ) {
  9524. const te = this.elements;
  9525. const me = matrix.elements;
  9526. for ( let i = 0; i < 16; i ++ ) {
  9527. if ( te[ i ] !== me[ i ] ) return false;
  9528. }
  9529. return true;
  9530. }
  9531. /**
  9532. * Sets the elements of the matrix from the given array.
  9533. *
  9534. * @param {Array<number>} array - The matrix elements in column-major order.
  9535. * @param {number} [offset=0] - Index of the first element in the array.
  9536. * @return {Matrix4} A reference to this matrix.
  9537. */
  9538. fromArray( array, offset = 0 ) {
  9539. for ( let i = 0; i < 16; i ++ ) {
  9540. this.elements[ i ] = array[ i + offset ];
  9541. }
  9542. return this;
  9543. }
  9544. /**
  9545. * Writes the elements of this matrix to the given array. If no array is provided,
  9546. * the method returns a new instance.
  9547. *
  9548. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9549. * @param {number} [offset=0] - Index of the first element in the array.
  9550. * @return {Array<number>} The matrix elements in column-major order.
  9551. */
  9552. toArray( array = [], offset = 0 ) {
  9553. const te = this.elements;
  9554. array[ offset ] = te[ 0 ];
  9555. array[ offset + 1 ] = te[ 1 ];
  9556. array[ offset + 2 ] = te[ 2 ];
  9557. array[ offset + 3 ] = te[ 3 ];
  9558. array[ offset + 4 ] = te[ 4 ];
  9559. array[ offset + 5 ] = te[ 5 ];
  9560. array[ offset + 6 ] = te[ 6 ];
  9561. array[ offset + 7 ] = te[ 7 ];
  9562. array[ offset + 8 ] = te[ 8 ];
  9563. array[ offset + 9 ] = te[ 9 ];
  9564. array[ offset + 10 ] = te[ 10 ];
  9565. array[ offset + 11 ] = te[ 11 ];
  9566. array[ offset + 12 ] = te[ 12 ];
  9567. array[ offset + 13 ] = te[ 13 ];
  9568. array[ offset + 14 ] = te[ 14 ];
  9569. array[ offset + 15 ] = te[ 15 ];
  9570. return array;
  9571. }
  9572. }
  9573. const _v1$5 = /*@__PURE__*/ new Vector3();
  9574. const _m1$2 = /*@__PURE__*/ new Matrix4();
  9575. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9576. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9577. const _x = /*@__PURE__*/ new Vector3();
  9578. const _y = /*@__PURE__*/ new Vector3();
  9579. const _z = /*@__PURE__*/ new Vector3();
  9580. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9581. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9582. /**
  9583. * A class representing Euler angles.
  9584. *
  9585. * Euler angles describe a rotational transformation by rotating an object on
  9586. * its various axes in specified amounts per axis, and a specified axis
  9587. * order.
  9588. *
  9589. * Iterating through an instance will yield its components (x, y, z,
  9590. * order) in the corresponding order.
  9591. *
  9592. * ```js
  9593. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9594. * const b = new THREE.Vector3( 1, 0, 1 );
  9595. * b.applyEuler(a);
  9596. * ```
  9597. */
  9598. class Euler {
  9599. /**
  9600. * Constructs a new euler instance.
  9601. *
  9602. * @param {number} [x=0] - The angle of the x axis in radians.
  9603. * @param {number} [y=0] - The angle of the y axis in radians.
  9604. * @param {number} [z=0] - The angle of the z axis in radians.
  9605. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9606. */
  9607. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9608. /**
  9609. * This flag can be used for type testing.
  9610. *
  9611. * @type {boolean}
  9612. * @readonly
  9613. * @default true
  9614. */
  9615. this.isEuler = true;
  9616. this._x = x;
  9617. this._y = y;
  9618. this._z = z;
  9619. this._order = order;
  9620. }
  9621. /**
  9622. * The angle of the x axis in radians.
  9623. *
  9624. * @type {number}
  9625. * @default 0
  9626. */
  9627. get x() {
  9628. return this._x;
  9629. }
  9630. set x( value ) {
  9631. this._x = value;
  9632. this._onChangeCallback();
  9633. }
  9634. /**
  9635. * The angle of the y axis in radians.
  9636. *
  9637. * @type {number}
  9638. * @default 0
  9639. */
  9640. get y() {
  9641. return this._y;
  9642. }
  9643. set y( value ) {
  9644. this._y = value;
  9645. this._onChangeCallback();
  9646. }
  9647. /**
  9648. * The angle of the z axis in radians.
  9649. *
  9650. * @type {number}
  9651. * @default 0
  9652. */
  9653. get z() {
  9654. return this._z;
  9655. }
  9656. set z( value ) {
  9657. this._z = value;
  9658. this._onChangeCallback();
  9659. }
  9660. /**
  9661. * A string representing the order that the rotations are applied.
  9662. *
  9663. * @type {string}
  9664. * @default 'XYZ'
  9665. */
  9666. get order() {
  9667. return this._order;
  9668. }
  9669. set order( value ) {
  9670. this._order = value;
  9671. this._onChangeCallback();
  9672. }
  9673. /**
  9674. * Sets the Euler components.
  9675. *
  9676. * @param {number} x - The angle of the x axis in radians.
  9677. * @param {number} y - The angle of the y axis in radians.
  9678. * @param {number} z - The angle of the z axis in radians.
  9679. * @param {string} [order] - A string representing the order that the rotations are applied.
  9680. * @return {Euler} A reference to this Euler instance.
  9681. */
  9682. set( x, y, z, order = this._order ) {
  9683. this._x = x;
  9684. this._y = y;
  9685. this._z = z;
  9686. this._order = order;
  9687. this._onChangeCallback();
  9688. return this;
  9689. }
  9690. /**
  9691. * Returns a new Euler instance with copied values from this instance.
  9692. *
  9693. * @return {Euler} A clone of this instance.
  9694. */
  9695. clone() {
  9696. return new this.constructor( this._x, this._y, this._z, this._order );
  9697. }
  9698. /**
  9699. * Copies the values of the given Euler instance to this instance.
  9700. *
  9701. * @param {Euler} euler - The Euler instance to copy.
  9702. * @return {Euler} A reference to this Euler instance.
  9703. */
  9704. copy( euler ) {
  9705. this._x = euler._x;
  9706. this._y = euler._y;
  9707. this._z = euler._z;
  9708. this._order = euler._order;
  9709. this._onChangeCallback();
  9710. return this;
  9711. }
  9712. /**
  9713. * Sets the angles of this Euler instance from a pure rotation matrix.
  9714. *
  9715. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9716. * @param {string} [order] - A string representing the order that the rotations are applied.
  9717. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9718. * @return {Euler} A reference to this Euler instance.
  9719. */
  9720. setFromRotationMatrix( m, order = this._order, update = true ) {
  9721. const te = m.elements;
  9722. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9723. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9724. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9725. switch ( order ) {
  9726. case 'XYZ':
  9727. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9728. if ( Math.abs( m13 ) < 0.9999999 ) {
  9729. this._x = Math.atan2( - m23, m33 );
  9730. this._z = Math.atan2( - m12, m11 );
  9731. } else {
  9732. this._x = Math.atan2( m32, m22 );
  9733. this._z = 0;
  9734. }
  9735. break;
  9736. case 'YXZ':
  9737. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9738. if ( Math.abs( m23 ) < 0.9999999 ) {
  9739. this._y = Math.atan2( m13, m33 );
  9740. this._z = Math.atan2( m21, m22 );
  9741. } else {
  9742. this._y = Math.atan2( - m31, m11 );
  9743. this._z = 0;
  9744. }
  9745. break;
  9746. case 'ZXY':
  9747. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9748. if ( Math.abs( m32 ) < 0.9999999 ) {
  9749. this._y = Math.atan2( - m31, m33 );
  9750. this._z = Math.atan2( - m12, m22 );
  9751. } else {
  9752. this._y = 0;
  9753. this._z = Math.atan2( m21, m11 );
  9754. }
  9755. break;
  9756. case 'ZYX':
  9757. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9758. if ( Math.abs( m31 ) < 0.9999999 ) {
  9759. this._x = Math.atan2( m32, m33 );
  9760. this._z = Math.atan2( m21, m11 );
  9761. } else {
  9762. this._x = 0;
  9763. this._z = Math.atan2( - m12, m22 );
  9764. }
  9765. break;
  9766. case 'YZX':
  9767. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9768. if ( Math.abs( m21 ) < 0.9999999 ) {
  9769. this._x = Math.atan2( - m23, m22 );
  9770. this._y = Math.atan2( - m31, m11 );
  9771. } else {
  9772. this._x = 0;
  9773. this._y = Math.atan2( m13, m33 );
  9774. }
  9775. break;
  9776. case 'XZY':
  9777. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9778. if ( Math.abs( m12 ) < 0.9999999 ) {
  9779. this._x = Math.atan2( m32, m22 );
  9780. this._y = Math.atan2( m13, m11 );
  9781. } else {
  9782. this._x = Math.atan2( - m23, m33 );
  9783. this._y = 0;
  9784. }
  9785. break;
  9786. default:
  9787. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9788. }
  9789. this._order = order;
  9790. if ( update === true ) this._onChangeCallback();
  9791. return this;
  9792. }
  9793. /**
  9794. * Sets the angles of this Euler instance from a normalized quaternion.
  9795. *
  9796. * @param {Quaternion} q - A normalized Quaternion.
  9797. * @param {string} [order] - A string representing the order that the rotations are applied.
  9798. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9799. * @return {Euler} A reference to this Euler instance.
  9800. */
  9801. setFromQuaternion( q, order, update ) {
  9802. _matrix$2.makeRotationFromQuaternion( q );
  9803. return this.setFromRotationMatrix( _matrix$2, order, update );
  9804. }
  9805. /**
  9806. * Sets the angles of this Euler instance from the given vector.
  9807. *
  9808. * @param {Vector3} v - The vector.
  9809. * @param {string} [order] - A string representing the order that the rotations are applied.
  9810. * @return {Euler} A reference to this Euler instance.
  9811. */
  9812. setFromVector3( v, order = this._order ) {
  9813. return this.set( v.x, v.y, v.z, order );
  9814. }
  9815. /**
  9816. * Resets the euler angle with a new order by creating a quaternion from this
  9817. * euler angle and then setting this euler angle with the quaternion and the
  9818. * new order.
  9819. *
  9820. * Warning: This discards revolution information.
  9821. *
  9822. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9823. * @return {Euler} A reference to this Euler instance.
  9824. */
  9825. reorder( newOrder ) {
  9826. _quaternion$3.setFromEuler( this );
  9827. return this.setFromQuaternion( _quaternion$3, newOrder );
  9828. }
  9829. /**
  9830. * Returns `true` if this Euler instance is equal with the given one.
  9831. *
  9832. * @param {Euler} euler - The Euler instance to test for equality.
  9833. * @return {boolean} Whether this Euler instance is equal with the given one.
  9834. */
  9835. equals( euler ) {
  9836. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9837. }
  9838. /**
  9839. * Sets this Euler instance's components to values from the given array. The first three
  9840. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9841. * defines the Euler order.
  9842. *
  9843. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9844. * @return {Euler} A reference to this Euler instance.
  9845. */
  9846. fromArray( array ) {
  9847. this._x = array[ 0 ];
  9848. this._y = array[ 1 ];
  9849. this._z = array[ 2 ];
  9850. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9851. this._onChangeCallback();
  9852. return this;
  9853. }
  9854. /**
  9855. * Writes the components of this Euler instance to the given array. If no array is provided,
  9856. * the method returns a new instance.
  9857. *
  9858. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9859. * @param {number} [offset=0] - Index of the first element in the array.
  9860. * @return {Array<number,number,number,string>} The Euler components.
  9861. */
  9862. toArray( array = [], offset = 0 ) {
  9863. array[ offset ] = this._x;
  9864. array[ offset + 1 ] = this._y;
  9865. array[ offset + 2 ] = this._z;
  9866. array[ offset + 3 ] = this._order;
  9867. return array;
  9868. }
  9869. _onChange( callback ) {
  9870. this._onChangeCallback = callback;
  9871. return this;
  9872. }
  9873. _onChangeCallback() {}
  9874. *[ Symbol.iterator ]() {
  9875. yield this._x;
  9876. yield this._y;
  9877. yield this._z;
  9878. yield this._order;
  9879. }
  9880. }
  9881. /**
  9882. * The default Euler angle order.
  9883. *
  9884. * @static
  9885. * @type {string}
  9886. * @default 'XYZ'
  9887. */
  9888. Euler.DEFAULT_ORDER = 'XYZ';
  9889. /**
  9890. * A layers object assigns an 3D object to 1 or more of 32
  9891. * layers numbered `0` to `31` - internally the layers are stored as a
  9892. * bit mask], and by default all 3D objects are a member of layer `0`.
  9893. *
  9894. * This can be used to control visibility - an object must share a layer with
  9895. * a camera to be visible when that camera's view is
  9896. * rendered.
  9897. *
  9898. * All classes that inherit from {@link Object3D} have an `layers` property which
  9899. * is an instance of this class.
  9900. */
  9901. class Layers {
  9902. /**
  9903. * Constructs a new layers instance, with membership
  9904. * initially set to layer `0`.
  9905. */
  9906. constructor() {
  9907. /**
  9908. * A bit mask storing which of the 32 layers this layers object is currently
  9909. * a member of.
  9910. *
  9911. * @type {number}
  9912. */
  9913. this.mask = 1 | 0;
  9914. }
  9915. /**
  9916. * Sets membership to the given layer, and remove membership all other layers.
  9917. *
  9918. * @param {number} layer - The layer to set.
  9919. */
  9920. set( layer ) {
  9921. this.mask = ( 1 << layer | 0 ) >>> 0;
  9922. }
  9923. /**
  9924. * Adds membership of the given layer.
  9925. *
  9926. * @param {number} layer - The layer to enable.
  9927. */
  9928. enable( layer ) {
  9929. this.mask |= 1 << layer | 0;
  9930. }
  9931. /**
  9932. * Adds membership to all layers.
  9933. */
  9934. enableAll() {
  9935. this.mask = 0xffffffff | 0;
  9936. }
  9937. /**
  9938. * Toggles the membership of the given layer.
  9939. *
  9940. * @param {number} layer - The layer to toggle.
  9941. */
  9942. toggle( layer ) {
  9943. this.mask ^= 1 << layer | 0;
  9944. }
  9945. /**
  9946. * Removes membership of the given layer.
  9947. *
  9948. * @param {number} layer - The layer to enable.
  9949. */
  9950. disable( layer ) {
  9951. this.mask &= ~ ( 1 << layer | 0 );
  9952. }
  9953. /**
  9954. * Removes the membership from all layers.
  9955. */
  9956. disableAll() {
  9957. this.mask = 0;
  9958. }
  9959. /**
  9960. * Returns `true` if this and the given layers object have at least one
  9961. * layer in common.
  9962. *
  9963. * @param {Layers} layers - The layers to test.
  9964. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  9965. */
  9966. test( layers ) {
  9967. return ( this.mask & layers.mask ) !== 0;
  9968. }
  9969. /**
  9970. * Returns `true` if the given layer is enabled.
  9971. *
  9972. * @param {number} layer - The layer to test.
  9973. * @return {boolean } Whether the given layer is enabled or not.
  9974. */
  9975. isEnabled( layer ) {
  9976. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  9977. }
  9978. }
  9979. let _object3DId = 0;
  9980. const _v1$4 = /*@__PURE__*/ new Vector3();
  9981. const _q1 = /*@__PURE__*/ new Quaternion();
  9982. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9983. const _target = /*@__PURE__*/ new Vector3();
  9984. const _position$3 = /*@__PURE__*/ new Vector3();
  9985. const _scale$2 = /*@__PURE__*/ new Vector3();
  9986. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  9987. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  9988. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  9989. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  9990. /**
  9991. * Fires when the object has been added to its parent object.
  9992. *
  9993. * @event Object3D#added
  9994. * @type {Object}
  9995. */
  9996. const _addedEvent = { type: 'added' };
  9997. /**
  9998. * Fires when the object has been removed from its parent object.
  9999. *
  10000. * @event Object3D#removed
  10001. * @type {Object}
  10002. */
  10003. const _removedEvent = { type: 'removed' };
  10004. /**
  10005. * Fires when a new child object has been added.
  10006. *
  10007. * @event Object3D#childadded
  10008. * @type {Object}
  10009. */
  10010. const _childaddedEvent = { type: 'childadded', child: null };
  10011. /**
  10012. * Fires when a child object has been removed.
  10013. *
  10014. * @event Object3D#childremoved
  10015. * @type {Object}
  10016. */
  10017. const _childremovedEvent = { type: 'childremoved', child: null };
  10018. /**
  10019. * This is the base class for most objects in three.js and provides a set of
  10020. * properties and methods for manipulating objects in 3D space.
  10021. *
  10022. * @augments EventDispatcher
  10023. */
  10024. class Object3D extends EventDispatcher {
  10025. /**
  10026. * Constructs a new 3D object.
  10027. */
  10028. constructor() {
  10029. super();
  10030. /**
  10031. * This flag can be used for type testing.
  10032. *
  10033. * @type {boolean}
  10034. * @readonly
  10035. * @default true
  10036. */
  10037. this.isObject3D = true;
  10038. /**
  10039. * The ID of the 3D object.
  10040. *
  10041. * @name Object3D#id
  10042. * @type {number}
  10043. * @readonly
  10044. */
  10045. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10046. /**
  10047. * The UUID of the 3D object.
  10048. *
  10049. * @type {string}
  10050. * @readonly
  10051. */
  10052. this.uuid = generateUUID();
  10053. /**
  10054. * The name of the 3D object.
  10055. *
  10056. * @type {string}
  10057. */
  10058. this.name = '';
  10059. /**
  10060. * The type property is used for detecting the object type
  10061. * in context of serialization/deserialization.
  10062. *
  10063. * @type {string}
  10064. * @readonly
  10065. */
  10066. this.type = 'Object3D';
  10067. /**
  10068. * A reference to the parent object.
  10069. *
  10070. * @type {?Object3D}
  10071. * @default null
  10072. */
  10073. this.parent = null;
  10074. /**
  10075. * An array holding the child 3D objects of this instance.
  10076. *
  10077. * @type {Array<Object3D>}
  10078. */
  10079. this.children = [];
  10080. /**
  10081. * Defines the `up` direction of the 3D object which influences
  10082. * the orientation via methods like {@link Object3D#lookAt}.
  10083. *
  10084. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10085. *
  10086. * @type {Vector3}
  10087. */
  10088. this.up = Object3D.DEFAULT_UP.clone();
  10089. const position = new Vector3();
  10090. const rotation = new Euler();
  10091. const quaternion = new Quaternion();
  10092. const scale = new Vector3( 1, 1, 1 );
  10093. function onRotationChange() {
  10094. quaternion.setFromEuler( rotation, false );
  10095. }
  10096. function onQuaternionChange() {
  10097. rotation.setFromQuaternion( quaternion, undefined, false );
  10098. }
  10099. rotation._onChange( onRotationChange );
  10100. quaternion._onChange( onQuaternionChange );
  10101. Object.defineProperties( this, {
  10102. /**
  10103. * Represents the object's local position.
  10104. *
  10105. * @name Object3D#position
  10106. * @type {Vector3}
  10107. * @default (0,0,0)
  10108. */
  10109. position: {
  10110. configurable: true,
  10111. enumerable: true,
  10112. value: position
  10113. },
  10114. /**
  10115. * Represents the object's local rotation as Euler angles, in radians.
  10116. *
  10117. * @name Object3D#rotation
  10118. * @type {Euler}
  10119. * @default (0,0,0)
  10120. */
  10121. rotation: {
  10122. configurable: true,
  10123. enumerable: true,
  10124. value: rotation
  10125. },
  10126. /**
  10127. * Represents the object's local rotation as Quaternions.
  10128. *
  10129. * @name Object3D#quaternion
  10130. * @type {Quaternion}
  10131. */
  10132. quaternion: {
  10133. configurable: true,
  10134. enumerable: true,
  10135. value: quaternion
  10136. },
  10137. /**
  10138. * Represents the object's local scale.
  10139. *
  10140. * @name Object3D#scale
  10141. * @type {Vector3}
  10142. * @default (1,1,1)
  10143. */
  10144. scale: {
  10145. configurable: true,
  10146. enumerable: true,
  10147. value: scale
  10148. },
  10149. /**
  10150. * Represents the object's model-view matrix.
  10151. *
  10152. * @name Object3D#modelViewMatrix
  10153. * @type {Matrix4}
  10154. */
  10155. modelViewMatrix: {
  10156. value: new Matrix4()
  10157. },
  10158. /**
  10159. * Represents the object's normal matrix.
  10160. *
  10161. * @name Object3D#normalMatrix
  10162. * @type {Matrix3}
  10163. */
  10164. normalMatrix: {
  10165. value: new Matrix3()
  10166. }
  10167. } );
  10168. /**
  10169. * Represents the object's transformation matrix in local space.
  10170. *
  10171. * @type {Matrix4}
  10172. */
  10173. this.matrix = new Matrix4();
  10174. /**
  10175. * Represents the object's transformation matrix in world space.
  10176. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10177. *
  10178. * @type {Matrix4}
  10179. */
  10180. this.matrixWorld = new Matrix4();
  10181. /**
  10182. * When set to `true`, the engine automatically computes the local matrix from position,
  10183. * rotation and scale every frame.
  10184. *
  10185. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10186. *
  10187. * @type {boolean}
  10188. * @default true
  10189. */
  10190. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10191. /**
  10192. * When set to `true`, the engine automatically computes the world matrix from the current local
  10193. * matrix and the object's transformation hierarchy.
  10194. *
  10195. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10196. *
  10197. * @type {boolean}
  10198. * @default true
  10199. */
  10200. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10201. /**
  10202. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10203. * to `false`.
  10204. *
  10205. * @type {boolean}
  10206. * @default false
  10207. */
  10208. this.matrixWorldNeedsUpdate = false;
  10209. /**
  10210. * The layer membership of the 3D object. The 3D object is only visible if it has
  10211. * at least one layer in common with the camera in use. This property can also be
  10212. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10213. *
  10214. * @type {Layers}
  10215. */
  10216. this.layers = new Layers();
  10217. /**
  10218. * When set to `true`, the 3D object gets rendered.
  10219. *
  10220. * @type {boolean}
  10221. * @default true
  10222. */
  10223. this.visible = true;
  10224. /**
  10225. * When set to `true`, the 3D object gets rendered into shadow maps.
  10226. *
  10227. * @type {boolean}
  10228. * @default false
  10229. */
  10230. this.castShadow = false;
  10231. /**
  10232. * When set to `true`, the 3D object is affected by shadows in the scene.
  10233. *
  10234. * @type {boolean}
  10235. * @default false
  10236. */
  10237. this.receiveShadow = false;
  10238. /**
  10239. * When set to `true`, the 3D object is honored by view frustum culling.
  10240. *
  10241. * @type {boolean}
  10242. * @default true
  10243. */
  10244. this.frustumCulled = true;
  10245. /**
  10246. * This value allows the default rendering order of scene graph objects to be
  10247. * overridden although opaque and transparent objects remain sorted independently.
  10248. * When this property is set for an instance of {@link Group},all descendants
  10249. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10250. * render order.
  10251. *
  10252. * @type {number}
  10253. * @default 0
  10254. */
  10255. this.renderOrder = 0;
  10256. /**
  10257. * An array holding the animation clips of the 3D object.
  10258. *
  10259. * @type {Array<AnimationClip>}
  10260. */
  10261. this.animations = [];
  10262. /**
  10263. * Custom depth material to be used when rendering to the depth map. Can only be used
  10264. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10265. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10266. * material for proper shadows.
  10267. *
  10268. * Only relevant in context of {@link WebGLRenderer}.
  10269. *
  10270. * @type {(Material|undefined)}
  10271. * @default undefined
  10272. */
  10273. this.customDepthMaterial = undefined;
  10274. /**
  10275. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10276. *
  10277. * Only relevant in context of {@link WebGLRenderer}.
  10278. *
  10279. * @type {(Material|undefined)}
  10280. * @default undefined
  10281. */
  10282. this.customDistanceMaterial = undefined;
  10283. /**
  10284. * An object that can be used to store custom data about the 3D object. It
  10285. * should not hold references to functions as these will not be cloned.
  10286. *
  10287. * @type {Object}
  10288. */
  10289. this.userData = {};
  10290. }
  10291. /**
  10292. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10293. *
  10294. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10295. * @param {Object3D} object - The 3D object.
  10296. * @param {Camera} camera - The camera that is used to render the scene.
  10297. * @param {Camera} shadowCamera - The shadow camera.
  10298. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10299. * @param {Material} depthMaterial - The depth material.
  10300. * @param {Object} group - The geometry group data.
  10301. */
  10302. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10303. /**
  10304. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10305. *
  10306. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10307. * @param {Object3D} object - The 3D object.
  10308. * @param {Camera} camera - The camera that is used to render the scene.
  10309. * @param {Camera} shadowCamera - The shadow camera.
  10310. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10311. * @param {Material} depthMaterial - The depth material.
  10312. * @param {Object} group - The geometry group data.
  10313. */
  10314. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10315. /**
  10316. * A callback that is executed immediately before a 3D object is rendered.
  10317. *
  10318. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10319. * @param {Object3D} object - The 3D object.
  10320. * @param {Camera} camera - The camera that is used to render the scene.
  10321. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10322. * @param {Material} material - The 3D object's material.
  10323. * @param {Object} group - The geometry group data.
  10324. */
  10325. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10326. /**
  10327. * A callback that is executed immediately after a 3D object is rendered.
  10328. *
  10329. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10330. * @param {Object3D} object - The 3D object.
  10331. * @param {Camera} camera - The camera that is used to render the scene.
  10332. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10333. * @param {Material} material - The 3D object's material.
  10334. * @param {Object} group - The geometry group data.
  10335. */
  10336. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10337. /**
  10338. * Applies the given transformation matrix to the object and updates the object's position,
  10339. * rotation and scale.
  10340. *
  10341. * @param {Matrix4} matrix - The transformation matrix.
  10342. */
  10343. applyMatrix4( matrix ) {
  10344. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10345. this.matrix.premultiply( matrix );
  10346. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10347. }
  10348. /**
  10349. * Applies a rotation represented by given the quaternion to the 3D object.
  10350. *
  10351. * @param {Quaternion} q - The quaternion.
  10352. * @return {Object3D} A reference to this instance.
  10353. */
  10354. applyQuaternion( q ) {
  10355. this.quaternion.premultiply( q );
  10356. return this;
  10357. }
  10358. /**
  10359. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10360. *
  10361. * @param {Vector3} axis - The (normalized) axis vector.
  10362. * @param {number} angle - The angle in radians.
  10363. */
  10364. setRotationFromAxisAngle( axis, angle ) {
  10365. // assumes axis is normalized
  10366. this.quaternion.setFromAxisAngle( axis, angle );
  10367. }
  10368. /**
  10369. * Sets the given rotation represented as Euler angles to the 3D object.
  10370. *
  10371. * @param {Euler} euler - The Euler angles.
  10372. */
  10373. setRotationFromEuler( euler ) {
  10374. this.quaternion.setFromEuler( euler, true );
  10375. }
  10376. /**
  10377. * Sets the given rotation represented as rotation matrix to the 3D object.
  10378. *
  10379. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10380. * a pure rotation matrix (i.e, unscaled).
  10381. */
  10382. setRotationFromMatrix( m ) {
  10383. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10384. this.quaternion.setFromRotationMatrix( m );
  10385. }
  10386. /**
  10387. * Sets the given rotation represented as a Quaternion to the 3D object.
  10388. *
  10389. * @param {Quaternion} q - The Quaternion
  10390. */
  10391. setRotationFromQuaternion( q ) {
  10392. // assumes q is normalized
  10393. this.quaternion.copy( q );
  10394. }
  10395. /**
  10396. * Rotates the 3D object along an axis in local space.
  10397. *
  10398. * @param {Vector3} axis - The (normalized) axis vector.
  10399. * @param {number} angle - The angle in radians.
  10400. * @return {Object3D} A reference to this instance.
  10401. */
  10402. rotateOnAxis( axis, angle ) {
  10403. // rotate object on axis in object space
  10404. // axis is assumed to be normalized
  10405. _q1.setFromAxisAngle( axis, angle );
  10406. this.quaternion.multiply( _q1 );
  10407. return this;
  10408. }
  10409. /**
  10410. * Rotates the 3D object along an axis in world space.
  10411. *
  10412. * @param {Vector3} axis - The (normalized) axis vector.
  10413. * @param {number} angle - The angle in radians.
  10414. * @return {Object3D} A reference to this instance.
  10415. */
  10416. rotateOnWorldAxis( axis, angle ) {
  10417. // rotate object on axis in world space
  10418. // axis is assumed to be normalized
  10419. // method assumes no rotated parent
  10420. _q1.setFromAxisAngle( axis, angle );
  10421. this.quaternion.premultiply( _q1 );
  10422. return this;
  10423. }
  10424. /**
  10425. * Rotates the 3D object around its X axis in local space.
  10426. *
  10427. * @param {number} angle - The angle in radians.
  10428. * @return {Object3D} A reference to this instance.
  10429. */
  10430. rotateX( angle ) {
  10431. return this.rotateOnAxis( _xAxis, angle );
  10432. }
  10433. /**
  10434. * Rotates the 3D object around its Y axis in local space.
  10435. *
  10436. * @param {number} angle - The angle in radians.
  10437. * @return {Object3D} A reference to this instance.
  10438. */
  10439. rotateY( angle ) {
  10440. return this.rotateOnAxis( _yAxis, angle );
  10441. }
  10442. /**
  10443. * Rotates the 3D object around its Z axis in local space.
  10444. *
  10445. * @param {number} angle - The angle in radians.
  10446. * @return {Object3D} A reference to this instance.
  10447. */
  10448. rotateZ( angle ) {
  10449. return this.rotateOnAxis( _zAxis, angle );
  10450. }
  10451. /**
  10452. * Translate the 3D object by a distance along the given axis in local space.
  10453. *
  10454. * @param {Vector3} axis - The (normalized) axis vector.
  10455. * @param {number} distance - The distance in world units.
  10456. * @return {Object3D} A reference to this instance.
  10457. */
  10458. translateOnAxis( axis, distance ) {
  10459. // translate object by distance along axis in object space
  10460. // axis is assumed to be normalized
  10461. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10462. this.position.add( _v1$4.multiplyScalar( distance ) );
  10463. return this;
  10464. }
  10465. /**
  10466. * Translate the 3D object by a distance along its X-axis in local space.
  10467. *
  10468. * @param {number} distance - The distance in world units.
  10469. * @return {Object3D} A reference to this instance.
  10470. */
  10471. translateX( distance ) {
  10472. return this.translateOnAxis( _xAxis, distance );
  10473. }
  10474. /**
  10475. * Translate the 3D object by a distance along its Y-axis in local space.
  10476. *
  10477. * @param {number} distance - The distance in world units.
  10478. * @return {Object3D} A reference to this instance.
  10479. */
  10480. translateY( distance ) {
  10481. return this.translateOnAxis( _yAxis, distance );
  10482. }
  10483. /**
  10484. * Translate the 3D object by a distance along its Z-axis in local space.
  10485. *
  10486. * @param {number} distance - The distance in world units.
  10487. * @return {Object3D} A reference to this instance.
  10488. */
  10489. translateZ( distance ) {
  10490. return this.translateOnAxis( _zAxis, distance );
  10491. }
  10492. /**
  10493. * Converts the given vector from this 3D object's local space to world space.
  10494. *
  10495. * @param {Vector3} vector - The vector to convert.
  10496. * @return {Vector3} The converted vector.
  10497. */
  10498. localToWorld( vector ) {
  10499. this.updateWorldMatrix( true, false );
  10500. return vector.applyMatrix4( this.matrixWorld );
  10501. }
  10502. /**
  10503. * Converts the given vector from this 3D object's word space to local space.
  10504. *
  10505. * @param {Vector3} vector - The vector to convert.
  10506. * @return {Vector3} The converted vector.
  10507. */
  10508. worldToLocal( vector ) {
  10509. this.updateWorldMatrix( true, false );
  10510. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  10511. }
  10512. /**
  10513. * Rotates the object to face a point in world space.
  10514. *
  10515. * This method does not support objects having non-uniformly-scaled parent(s).
  10516. *
  10517. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10518. * @param {number} [y] - The y coordinate in world space.
  10519. * @param {number} [z] - The z coordinate in world space.
  10520. */
  10521. lookAt( x, y, z ) {
  10522. // This method does not support objects having non-uniformly-scaled parent(s)
  10523. if ( x.isVector3 ) {
  10524. _target.copy( x );
  10525. } else {
  10526. _target.set( x, y, z );
  10527. }
  10528. const parent = this.parent;
  10529. this.updateWorldMatrix( true, false );
  10530. _position$3.setFromMatrixPosition( this.matrixWorld );
  10531. if ( this.isCamera || this.isLight ) {
  10532. _m1$1.lookAt( _position$3, _target, this.up );
  10533. } else {
  10534. _m1$1.lookAt( _target, _position$3, this.up );
  10535. }
  10536. this.quaternion.setFromRotationMatrix( _m1$1 );
  10537. if ( parent ) {
  10538. _m1$1.extractRotation( parent.matrixWorld );
  10539. _q1.setFromRotationMatrix( _m1$1 );
  10540. this.quaternion.premultiply( _q1.invert() );
  10541. }
  10542. }
  10543. /**
  10544. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10545. * objects may be added. Any current parent on an object passed in here will be
  10546. * removed, since an object can have at most one parent.
  10547. *
  10548. * @fires Object3D#added
  10549. * @fires Object3D#childadded
  10550. * @param {Object3D} object - The 3D object to add.
  10551. * @return {Object3D} A reference to this instance.
  10552. */
  10553. add( object ) {
  10554. if ( arguments.length > 1 ) {
  10555. for ( let i = 0; i < arguments.length; i ++ ) {
  10556. this.add( arguments[ i ] );
  10557. }
  10558. return this;
  10559. }
  10560. if ( object === this ) {
  10561. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  10562. return this;
  10563. }
  10564. if ( object && object.isObject3D ) {
  10565. object.removeFromParent();
  10566. object.parent = this;
  10567. this.children.push( object );
  10568. object.dispatchEvent( _addedEvent );
  10569. _childaddedEvent.child = object;
  10570. this.dispatchEvent( _childaddedEvent );
  10571. _childaddedEvent.child = null;
  10572. } else {
  10573. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  10574. }
  10575. return this;
  10576. }
  10577. /**
  10578. * Removes the given 3D object as child from this 3D object.
  10579. * An arbitrary number of objects may be removed.
  10580. *
  10581. * @fires Object3D#removed
  10582. * @fires Object3D#childremoved
  10583. * @param {Object3D} object - The 3D object to remove.
  10584. * @return {Object3D} A reference to this instance.
  10585. */
  10586. remove( object ) {
  10587. if ( arguments.length > 1 ) {
  10588. for ( let i = 0; i < arguments.length; i ++ ) {
  10589. this.remove( arguments[ i ] );
  10590. }
  10591. return this;
  10592. }
  10593. const index = this.children.indexOf( object );
  10594. if ( index !== -1 ) {
  10595. object.parent = null;
  10596. this.children.splice( index, 1 );
  10597. object.dispatchEvent( _removedEvent );
  10598. _childremovedEvent.child = object;
  10599. this.dispatchEvent( _childremovedEvent );
  10600. _childremovedEvent.child = null;
  10601. }
  10602. return this;
  10603. }
  10604. /**
  10605. * Removes this 3D object from its current parent.
  10606. *
  10607. * @fires Object3D#removed
  10608. * @fires Object3D#childremoved
  10609. * @return {Object3D} A reference to this instance.
  10610. */
  10611. removeFromParent() {
  10612. const parent = this.parent;
  10613. if ( parent !== null ) {
  10614. parent.remove( this );
  10615. }
  10616. return this;
  10617. }
  10618. /**
  10619. * Removes all child objects.
  10620. *
  10621. * @fires Object3D#removed
  10622. * @fires Object3D#childremoved
  10623. * @return {Object3D} A reference to this instance.
  10624. */
  10625. clear() {
  10626. return this.remove( ... this.children );
  10627. }
  10628. /**
  10629. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10630. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10631. *
  10632. * @fires Object3D#added
  10633. * @fires Object3D#childadded
  10634. * @param {Object3D} object - The 3D object to attach.
  10635. * @return {Object3D} A reference to this instance.
  10636. */
  10637. attach( object ) {
  10638. // adds object as a child of this, while maintaining the object's world transform
  10639. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10640. this.updateWorldMatrix( true, false );
  10641. _m1$1.copy( this.matrixWorld ).invert();
  10642. if ( object.parent !== null ) {
  10643. object.parent.updateWorldMatrix( true, false );
  10644. _m1$1.multiply( object.parent.matrixWorld );
  10645. }
  10646. object.applyMatrix4( _m1$1 );
  10647. object.removeFromParent();
  10648. object.parent = this;
  10649. this.children.push( object );
  10650. object.updateWorldMatrix( false, true );
  10651. object.dispatchEvent( _addedEvent );
  10652. _childaddedEvent.child = object;
  10653. this.dispatchEvent( _childaddedEvent );
  10654. _childaddedEvent.child = null;
  10655. return this;
  10656. }
  10657. /**
  10658. * Searches through the 3D object and its children, starting with the 3D object
  10659. * itself, and returns the first with a matching ID.
  10660. *
  10661. * @param {number} id - The id.
  10662. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10663. */
  10664. getObjectById( id ) {
  10665. return this.getObjectByProperty( 'id', id );
  10666. }
  10667. /**
  10668. * Searches through the 3D object and its children, starting with the 3D object
  10669. * itself, and returns the first with a matching name.
  10670. *
  10671. * @param {string} name - The name.
  10672. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10673. */
  10674. getObjectByName( name ) {
  10675. return this.getObjectByProperty( 'name', name );
  10676. }
  10677. /**
  10678. * Searches through the 3D object and its children, starting with the 3D object
  10679. * itself, and returns the first with a matching property value.
  10680. *
  10681. * @param {string} name - The name of the property.
  10682. * @param {any} value - The value.
  10683. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10684. */
  10685. getObjectByProperty( name, value ) {
  10686. if ( this[ name ] === value ) return this;
  10687. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10688. const child = this.children[ i ];
  10689. const object = child.getObjectByProperty( name, value );
  10690. if ( object !== undefined ) {
  10691. return object;
  10692. }
  10693. }
  10694. return undefined;
  10695. }
  10696. /**
  10697. * Searches through the 3D object and its children, starting with the 3D object
  10698. * itself, and returns all 3D objects with a matching property value.
  10699. *
  10700. * @param {string} name - The name of the property.
  10701. * @param {any} value - The value.
  10702. * @param {Array<Object3D>} result - The method stores the result in this array.
  10703. * @return {Array<Object3D>} The found 3D objects.
  10704. */
  10705. getObjectsByProperty( name, value, result = [] ) {
  10706. if ( this[ name ] === value ) result.push( this );
  10707. const children = this.children;
  10708. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10709. children[ i ].getObjectsByProperty( name, value, result );
  10710. }
  10711. return result;
  10712. }
  10713. /**
  10714. * Returns a vector representing the position of the 3D object in world space.
  10715. *
  10716. * @param {Vector3} target - The target vector the result is stored to.
  10717. * @return {Vector3} The 3D object's position in world space.
  10718. */
  10719. getWorldPosition( target ) {
  10720. this.updateWorldMatrix( true, false );
  10721. return target.setFromMatrixPosition( this.matrixWorld );
  10722. }
  10723. /**
  10724. * Returns a Quaternion representing the position of the 3D object in world space.
  10725. *
  10726. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10727. * @return {Quaternion} The 3D object's rotation in world space.
  10728. */
  10729. getWorldQuaternion( target ) {
  10730. this.updateWorldMatrix( true, false );
  10731. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10732. return target;
  10733. }
  10734. /**
  10735. * Returns a vector representing the scale of the 3D object in world space.
  10736. *
  10737. * @param {Vector3} target - The target vector the result is stored to.
  10738. * @return {Vector3} The 3D object's scale in world space.
  10739. */
  10740. getWorldScale( target ) {
  10741. this.updateWorldMatrix( true, false );
  10742. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10743. return target;
  10744. }
  10745. /**
  10746. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10747. *
  10748. * @param {Vector3} target - The target vector the result is stored to.
  10749. * @return {Vector3} The 3D object's direction in world space.
  10750. */
  10751. getWorldDirection( target ) {
  10752. this.updateWorldMatrix( true, false );
  10753. const e = this.matrixWorld.elements;
  10754. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10755. }
  10756. /**
  10757. * Abstract method to get intersections between a casted ray and this
  10758. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10759. * implement this method in order to use raycasting.
  10760. *
  10761. * @abstract
  10762. * @param {Raycaster} raycaster - The raycaster.
  10763. * @param {Array<Object>} intersects - An array holding the result of the method.
  10764. */
  10765. raycast( /* raycaster, intersects */ ) {}
  10766. /**
  10767. * Executes the callback on this 3D object and all descendants.
  10768. *
  10769. * Note: Modifying the scene graph inside the callback is discouraged.
  10770. *
  10771. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10772. */
  10773. traverse( callback ) {
  10774. callback( this );
  10775. const children = this.children;
  10776. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10777. children[ i ].traverse( callback );
  10778. }
  10779. }
  10780. /**
  10781. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10782. * Descendants of invisible 3D objects are not traversed.
  10783. *
  10784. * Note: Modifying the scene graph inside the callback is discouraged.
  10785. *
  10786. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10787. */
  10788. traverseVisible( callback ) {
  10789. if ( this.visible === false ) return;
  10790. callback( this );
  10791. const children = this.children;
  10792. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10793. children[ i ].traverseVisible( callback );
  10794. }
  10795. }
  10796. /**
  10797. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10798. *
  10799. * Note: Modifying the scene graph inside the callback is discouraged.
  10800. *
  10801. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10802. */
  10803. traverseAncestors( callback ) {
  10804. const parent = this.parent;
  10805. if ( parent !== null ) {
  10806. callback( parent );
  10807. parent.traverseAncestors( callback );
  10808. }
  10809. }
  10810. /**
  10811. * Updates the transformation matrix in local space by computing it from the current
  10812. * position, rotation and scale values.
  10813. */
  10814. updateMatrix() {
  10815. this.matrix.compose( this.position, this.quaternion, this.scale );
  10816. this.matrixWorldNeedsUpdate = true;
  10817. }
  10818. /**
  10819. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10820. *
  10821. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10822. * local space. The computation of the local and world matrix can be controlled with the
  10823. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10824. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10825. *
  10826. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10827. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10828. */
  10829. updateMatrixWorld( force ) {
  10830. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10831. if ( this.matrixWorldNeedsUpdate || force ) {
  10832. if ( this.matrixWorldAutoUpdate === true ) {
  10833. if ( this.parent === null ) {
  10834. this.matrixWorld.copy( this.matrix );
  10835. } else {
  10836. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10837. }
  10838. }
  10839. this.matrixWorldNeedsUpdate = false;
  10840. force = true;
  10841. }
  10842. // make sure descendants are updated if required
  10843. const children = this.children;
  10844. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10845. const child = children[ i ];
  10846. child.updateMatrixWorld( force );
  10847. }
  10848. }
  10849. /**
  10850. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10851. * update of ancestor and descendant nodes.
  10852. *
  10853. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10854. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10855. */
  10856. updateWorldMatrix( updateParents, updateChildren ) {
  10857. const parent = this.parent;
  10858. if ( updateParents === true && parent !== null ) {
  10859. parent.updateWorldMatrix( true, false );
  10860. }
  10861. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10862. if ( this.matrixWorldAutoUpdate === true ) {
  10863. if ( this.parent === null ) {
  10864. this.matrixWorld.copy( this.matrix );
  10865. } else {
  10866. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10867. }
  10868. }
  10869. // make sure descendants are updated
  10870. if ( updateChildren === true ) {
  10871. const children = this.children;
  10872. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10873. const child = children[ i ];
  10874. child.updateWorldMatrix( false, true );
  10875. }
  10876. }
  10877. }
  10878. /**
  10879. * Serializes the 3D object into JSON.
  10880. *
  10881. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10882. * @return {Object} A JSON object representing the serialized 3D object.
  10883. * @see {@link ObjectLoader#parse}
  10884. */
  10885. toJSON( meta ) {
  10886. // meta is a string when called from JSON.stringify
  10887. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10888. const output = {};
  10889. // meta is a hash used to collect geometries, materials.
  10890. // not providing it implies that this is the root object
  10891. // being serialized.
  10892. if ( isRootObject ) {
  10893. // initialize meta obj
  10894. meta = {
  10895. geometries: {},
  10896. materials: {},
  10897. textures: {},
  10898. images: {},
  10899. shapes: {},
  10900. skeletons: {},
  10901. animations: {},
  10902. nodes: {}
  10903. };
  10904. output.metadata = {
  10905. version: 4.7,
  10906. type: 'Object',
  10907. generator: 'Object3D.toJSON'
  10908. };
  10909. }
  10910. // standard Object3D serialization
  10911. const object = {};
  10912. object.uuid = this.uuid;
  10913. object.type = this.type;
  10914. if ( this.name !== '' ) object.name = this.name;
  10915. if ( this.castShadow === true ) object.castShadow = true;
  10916. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10917. if ( this.visible === false ) object.visible = false;
  10918. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10919. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10920. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10921. object.layers = this.layers.mask;
  10922. object.matrix = this.matrix.toArray();
  10923. object.up = this.up.toArray();
  10924. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10925. // object specific properties
  10926. if ( this.isInstancedMesh ) {
  10927. object.type = 'InstancedMesh';
  10928. object.count = this.count;
  10929. object.instanceMatrix = this.instanceMatrix.toJSON();
  10930. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10931. }
  10932. if ( this.isBatchedMesh ) {
  10933. object.type = 'BatchedMesh';
  10934. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10935. object.sortObjects = this.sortObjects;
  10936. object.drawRanges = this._drawRanges;
  10937. object.reservedRanges = this._reservedRanges;
  10938. object.geometryInfo = this._geometryInfo.map( info => ( {
  10939. ...info,
  10940. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  10941. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  10942. } ) );
  10943. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  10944. object.availableInstanceIds = this._availableInstanceIds.slice();
  10945. object.availableGeometryIds = this._availableGeometryIds.slice();
  10946. object.nextIndexStart = this._nextIndexStart;
  10947. object.nextVertexStart = this._nextVertexStart;
  10948. object.geometryCount = this._geometryCount;
  10949. object.maxInstanceCount = this._maxInstanceCount;
  10950. object.maxVertexCount = this._maxVertexCount;
  10951. object.maxIndexCount = this._maxIndexCount;
  10952. object.geometryInitialized = this._geometryInitialized;
  10953. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10954. object.indirectTexture = this._indirectTexture.toJSON( meta );
  10955. if ( this._colorsTexture !== null ) {
  10956. object.colorsTexture = this._colorsTexture.toJSON( meta );
  10957. }
  10958. if ( this.boundingSphere !== null ) {
  10959. object.boundingSphere = this.boundingSphere.toJSON();
  10960. }
  10961. if ( this.boundingBox !== null ) {
  10962. object.boundingBox = this.boundingBox.toJSON();
  10963. }
  10964. }
  10965. //
  10966. function serialize( library, element ) {
  10967. if ( library[ element.uuid ] === undefined ) {
  10968. library[ element.uuid ] = element.toJSON( meta );
  10969. }
  10970. return element.uuid;
  10971. }
  10972. if ( this.isScene ) {
  10973. if ( this.background ) {
  10974. if ( this.background.isColor ) {
  10975. object.background = this.background.toJSON();
  10976. } else if ( this.background.isTexture ) {
  10977. object.background = this.background.toJSON( meta ).uuid;
  10978. }
  10979. }
  10980. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10981. object.environment = this.environment.toJSON( meta ).uuid;
  10982. }
  10983. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10984. object.geometry = serialize( meta.geometries, this.geometry );
  10985. const parameters = this.geometry.parameters;
  10986. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10987. const shapes = parameters.shapes;
  10988. if ( Array.isArray( shapes ) ) {
  10989. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10990. const shape = shapes[ i ];
  10991. serialize( meta.shapes, shape );
  10992. }
  10993. } else {
  10994. serialize( meta.shapes, shapes );
  10995. }
  10996. }
  10997. }
  10998. if ( this.isSkinnedMesh ) {
  10999. object.bindMode = this.bindMode;
  11000. object.bindMatrix = this.bindMatrix.toArray();
  11001. if ( this.skeleton !== undefined ) {
  11002. serialize( meta.skeletons, this.skeleton );
  11003. object.skeleton = this.skeleton.uuid;
  11004. }
  11005. }
  11006. if ( this.material !== undefined ) {
  11007. if ( Array.isArray( this.material ) ) {
  11008. const uuids = [];
  11009. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11010. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11011. }
  11012. object.material = uuids;
  11013. } else {
  11014. object.material = serialize( meta.materials, this.material );
  11015. }
  11016. }
  11017. //
  11018. if ( this.children.length > 0 ) {
  11019. object.children = [];
  11020. for ( let i = 0; i < this.children.length; i ++ ) {
  11021. object.children.push( this.children[ i ].toJSON( meta ).object );
  11022. }
  11023. }
  11024. //
  11025. if ( this.animations.length > 0 ) {
  11026. object.animations = [];
  11027. for ( let i = 0; i < this.animations.length; i ++ ) {
  11028. const animation = this.animations[ i ];
  11029. object.animations.push( serialize( meta.animations, animation ) );
  11030. }
  11031. }
  11032. if ( isRootObject ) {
  11033. const geometries = extractFromCache( meta.geometries );
  11034. const materials = extractFromCache( meta.materials );
  11035. const textures = extractFromCache( meta.textures );
  11036. const images = extractFromCache( meta.images );
  11037. const shapes = extractFromCache( meta.shapes );
  11038. const skeletons = extractFromCache( meta.skeletons );
  11039. const animations = extractFromCache( meta.animations );
  11040. const nodes = extractFromCache( meta.nodes );
  11041. if ( geometries.length > 0 ) output.geometries = geometries;
  11042. if ( materials.length > 0 ) output.materials = materials;
  11043. if ( textures.length > 0 ) output.textures = textures;
  11044. if ( images.length > 0 ) output.images = images;
  11045. if ( shapes.length > 0 ) output.shapes = shapes;
  11046. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11047. if ( animations.length > 0 ) output.animations = animations;
  11048. if ( nodes.length > 0 ) output.nodes = nodes;
  11049. }
  11050. output.object = object;
  11051. return output;
  11052. // extract data from the cache hash
  11053. // remove metadata on each item
  11054. // and return as array
  11055. function extractFromCache( cache ) {
  11056. const values = [];
  11057. for ( const key in cache ) {
  11058. const data = cache[ key ];
  11059. delete data.metadata;
  11060. values.push( data );
  11061. }
  11062. return values;
  11063. }
  11064. }
  11065. /**
  11066. * Returns a new 3D object with copied values from this instance.
  11067. *
  11068. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11069. * @return {Object3D} A clone of this instance.
  11070. */
  11071. clone( recursive ) {
  11072. return new this.constructor().copy( this, recursive );
  11073. }
  11074. /**
  11075. * Copies the values of the given 3D object to this instance.
  11076. *
  11077. * @param {Object3D} source - The 3D object to copy.
  11078. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11079. * @return {Object3D} A reference to this instance.
  11080. */
  11081. copy( source, recursive = true ) {
  11082. this.name = source.name;
  11083. this.up.copy( source.up );
  11084. this.position.copy( source.position );
  11085. this.rotation.order = source.rotation.order;
  11086. this.quaternion.copy( source.quaternion );
  11087. this.scale.copy( source.scale );
  11088. this.matrix.copy( source.matrix );
  11089. this.matrixWorld.copy( source.matrixWorld );
  11090. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11091. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11092. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11093. this.layers.mask = source.layers.mask;
  11094. this.visible = source.visible;
  11095. this.castShadow = source.castShadow;
  11096. this.receiveShadow = source.receiveShadow;
  11097. this.frustumCulled = source.frustumCulled;
  11098. this.renderOrder = source.renderOrder;
  11099. this.animations = source.animations.slice();
  11100. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11101. if ( recursive === true ) {
  11102. for ( let i = 0; i < source.children.length; i ++ ) {
  11103. const child = source.children[ i ];
  11104. this.add( child.clone() );
  11105. }
  11106. }
  11107. return this;
  11108. }
  11109. }
  11110. /**
  11111. * The default up direction for objects, also used as the default
  11112. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11113. *
  11114. * @static
  11115. * @type {Vector3}
  11116. * @default (0,1,0)
  11117. */
  11118. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11119. /**
  11120. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11121. * newly created 3D objects.
  11122. *
  11123. * @static
  11124. * @type {boolean}
  11125. * @default true
  11126. */
  11127. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11128. /**
  11129. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11130. * newly created 3D objects.
  11131. *
  11132. * @static
  11133. * @type {boolean}
  11134. * @default true
  11135. */
  11136. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11137. const _v0$1 = /*@__PURE__*/ new Vector3();
  11138. const _v1$3 = /*@__PURE__*/ new Vector3();
  11139. const _v2$2 = /*@__PURE__*/ new Vector3();
  11140. const _v3$2 = /*@__PURE__*/ new Vector3();
  11141. const _vab = /*@__PURE__*/ new Vector3();
  11142. const _vac = /*@__PURE__*/ new Vector3();
  11143. const _vbc = /*@__PURE__*/ new Vector3();
  11144. const _vap = /*@__PURE__*/ new Vector3();
  11145. const _vbp = /*@__PURE__*/ new Vector3();
  11146. const _vcp = /*@__PURE__*/ new Vector3();
  11147. const _v40 = /*@__PURE__*/ new Vector4();
  11148. const _v41 = /*@__PURE__*/ new Vector4();
  11149. const _v42 = /*@__PURE__*/ new Vector4();
  11150. /**
  11151. * A geometric triangle as defined by three vectors representing its three corners.
  11152. */
  11153. class Triangle {
  11154. /**
  11155. * Constructs a new triangle.
  11156. *
  11157. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11158. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11159. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11160. */
  11161. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11162. /**
  11163. * The first corner of the triangle.
  11164. *
  11165. * @type {Vector3}
  11166. */
  11167. this.a = a;
  11168. /**
  11169. * The second corner of the triangle.
  11170. *
  11171. * @type {Vector3}
  11172. */
  11173. this.b = b;
  11174. /**
  11175. * The third corner of the triangle.
  11176. *
  11177. * @type {Vector3}
  11178. */
  11179. this.c = c;
  11180. }
  11181. /**
  11182. * Computes the normal vector of a triangle.
  11183. *
  11184. * @param {Vector3} a - The first corner of the triangle.
  11185. * @param {Vector3} b - The second corner of the triangle.
  11186. * @param {Vector3} c - The third corner of the triangle.
  11187. * @param {Vector3} target - The target vector that is used to store the method's result.
  11188. * @return {Vector3} The triangle's normal.
  11189. */
  11190. static getNormal( a, b, c, target ) {
  11191. target.subVectors( c, b );
  11192. _v0$1.subVectors( a, b );
  11193. target.cross( _v0$1 );
  11194. const targetLengthSq = target.lengthSq();
  11195. if ( targetLengthSq > 0 ) {
  11196. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11197. }
  11198. return target.set( 0, 0, 0 );
  11199. }
  11200. /**
  11201. * Computes a barycentric coordinates from the given vector.
  11202. * Returns `null` if the triangle is degenerate.
  11203. *
  11204. * @param {Vector3} point - A point in 3D space.
  11205. * @param {Vector3} a - The first corner of the triangle.
  11206. * @param {Vector3} b - The second corner of the triangle.
  11207. * @param {Vector3} c - The third corner of the triangle.
  11208. * @param {Vector3} target - The target vector that is used to store the method's result.
  11209. * @return {?Vector3} The barycentric coordinates for the given point
  11210. */
  11211. static getBarycoord( point, a, b, c, target ) {
  11212. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11213. _v0$1.subVectors( c, a );
  11214. _v1$3.subVectors( b, a );
  11215. _v2$2.subVectors( point, a );
  11216. const dot00 = _v0$1.dot( _v0$1 );
  11217. const dot01 = _v0$1.dot( _v1$3 );
  11218. const dot02 = _v0$1.dot( _v2$2 );
  11219. const dot11 = _v1$3.dot( _v1$3 );
  11220. const dot12 = _v1$3.dot( _v2$2 );
  11221. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11222. // collinear or singular triangle
  11223. if ( denom === 0 ) {
  11224. target.set( 0, 0, 0 );
  11225. return null;
  11226. }
  11227. const invDenom = 1 / denom;
  11228. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11229. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11230. // barycentric coordinates must always sum to 1
  11231. return target.set( 1 - u - v, v, u );
  11232. }
  11233. /**
  11234. * Returns `true` if the given point, when projected onto the plane of the
  11235. * triangle, lies within the triangle.
  11236. *
  11237. * @param {Vector3} point - The point in 3D space to test.
  11238. * @param {Vector3} a - The first corner of the triangle.
  11239. * @param {Vector3} b - The second corner of the triangle.
  11240. * @param {Vector3} c - The third corner of the triangle.
  11241. * @return {boolean} Whether the given point, when projected onto the plane of the
  11242. * triangle, lies within the triangle or not.
  11243. */
  11244. static containsPoint( point, a, b, c ) {
  11245. // if the triangle is degenerate then we can't contain a point
  11246. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11247. return false;
  11248. }
  11249. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11250. }
  11251. /**
  11252. * Computes the value barycentrically interpolated for the given point on the
  11253. * triangle. Returns `null` if the triangle is degenerate.
  11254. *
  11255. * @param {Vector3} point - Position of interpolated point.
  11256. * @param {Vector3} p1 - The first corner of the triangle.
  11257. * @param {Vector3} p2 - The second corner of the triangle.
  11258. * @param {Vector3} p3 - The third corner of the triangle.
  11259. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11260. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11261. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11262. * @param {Vector3} target - The target vector that is used to store the method's result.
  11263. * @return {?Vector3} The interpolated value.
  11264. */
  11265. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11266. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11267. target.x = 0;
  11268. target.y = 0;
  11269. if ( 'z' in target ) target.z = 0;
  11270. if ( 'w' in target ) target.w = 0;
  11271. return null;
  11272. }
  11273. target.setScalar( 0 );
  11274. target.addScaledVector( v1, _v3$2.x );
  11275. target.addScaledVector( v2, _v3$2.y );
  11276. target.addScaledVector( v3, _v3$2.z );
  11277. return target;
  11278. }
  11279. /**
  11280. * Computes the value barycentrically interpolated for the given attribute and indices.
  11281. *
  11282. * @param {BufferAttribute} attr - The attribute to interpolate.
  11283. * @param {number} i1 - Index of first vertex.
  11284. * @param {number} i2 - Index of second vertex.
  11285. * @param {number} i3 - Index of third vertex.
  11286. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11287. * @param {Vector3} target - The target vector that is used to store the method's result.
  11288. * @return {Vector3} The interpolated attribute value.
  11289. */
  11290. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11291. _v40.setScalar( 0 );
  11292. _v41.setScalar( 0 );
  11293. _v42.setScalar( 0 );
  11294. _v40.fromBufferAttribute( attr, i1 );
  11295. _v41.fromBufferAttribute( attr, i2 );
  11296. _v42.fromBufferAttribute( attr, i3 );
  11297. target.setScalar( 0 );
  11298. target.addScaledVector( _v40, barycoord.x );
  11299. target.addScaledVector( _v41, barycoord.y );
  11300. target.addScaledVector( _v42, barycoord.z );
  11301. return target;
  11302. }
  11303. /**
  11304. * Returns `true` if the triangle is oriented towards the given direction.
  11305. *
  11306. * @param {Vector3} a - The first corner of the triangle.
  11307. * @param {Vector3} b - The second corner of the triangle.
  11308. * @param {Vector3} c - The third corner of the triangle.
  11309. * @param {Vector3} direction - The (normalized) direction vector.
  11310. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11311. */
  11312. static isFrontFacing( a, b, c, direction ) {
  11313. _v0$1.subVectors( c, b );
  11314. _v1$3.subVectors( a, b );
  11315. // strictly front facing
  11316. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11317. }
  11318. /**
  11319. * Sets the triangle's vertices by copying the given values.
  11320. *
  11321. * @param {Vector3} a - The first corner of the triangle.
  11322. * @param {Vector3} b - The second corner of the triangle.
  11323. * @param {Vector3} c - The third corner of the triangle.
  11324. * @return {Triangle} A reference to this triangle.
  11325. */
  11326. set( a, b, c ) {
  11327. this.a.copy( a );
  11328. this.b.copy( b );
  11329. this.c.copy( c );
  11330. return this;
  11331. }
  11332. /**
  11333. * Sets the triangle's vertices by copying the given array values.
  11334. *
  11335. * @param {Array<Vector3>} points - An array with 3D points.
  11336. * @param {number} i0 - The array index representing the first corner of the triangle.
  11337. * @param {number} i1 - The array index representing the second corner of the triangle.
  11338. * @param {number} i2 - The array index representing the third corner of the triangle.
  11339. * @return {Triangle} A reference to this triangle.
  11340. */
  11341. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11342. this.a.copy( points[ i0 ] );
  11343. this.b.copy( points[ i1 ] );
  11344. this.c.copy( points[ i2 ] );
  11345. return this;
  11346. }
  11347. /**
  11348. * Sets the triangle's vertices by copying the given attribute values.
  11349. *
  11350. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11351. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11352. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11353. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11354. * @return {Triangle} A reference to this triangle.
  11355. */
  11356. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11357. this.a.fromBufferAttribute( attribute, i0 );
  11358. this.b.fromBufferAttribute( attribute, i1 );
  11359. this.c.fromBufferAttribute( attribute, i2 );
  11360. return this;
  11361. }
  11362. /**
  11363. * Returns a new triangle with copied values from this instance.
  11364. *
  11365. * @return {Triangle} A clone of this instance.
  11366. */
  11367. clone() {
  11368. return new this.constructor().copy( this );
  11369. }
  11370. /**
  11371. * Copies the values of the given triangle to this instance.
  11372. *
  11373. * @param {Triangle} triangle - The triangle to copy.
  11374. * @return {Triangle} A reference to this triangle.
  11375. */
  11376. copy( triangle ) {
  11377. this.a.copy( triangle.a );
  11378. this.b.copy( triangle.b );
  11379. this.c.copy( triangle.c );
  11380. return this;
  11381. }
  11382. /**
  11383. * Computes the area of the triangle.
  11384. *
  11385. * @return {number} The triangle's area.
  11386. */
  11387. getArea() {
  11388. _v0$1.subVectors( this.c, this.b );
  11389. _v1$3.subVectors( this.a, this.b );
  11390. return _v0$1.cross( _v1$3 ).length() * 0.5;
  11391. }
  11392. /**
  11393. * Computes the midpoint of the triangle.
  11394. *
  11395. * @param {Vector3} target - The target vector that is used to store the method's result.
  11396. * @return {Vector3} The triangle's midpoint.
  11397. */
  11398. getMidpoint( target ) {
  11399. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11400. }
  11401. /**
  11402. * Computes the normal of the triangle.
  11403. *
  11404. * @param {Vector3} target - The target vector that is used to store the method's result.
  11405. * @return {Vector3} The triangle's normal.
  11406. */
  11407. getNormal( target ) {
  11408. return Triangle.getNormal( this.a, this.b, this.c, target );
  11409. }
  11410. /**
  11411. * Computes a plane the triangle lies within.
  11412. *
  11413. * @param {Plane} target - The target vector that is used to store the method's result.
  11414. * @return {Plane} The plane the triangle lies within.
  11415. */
  11416. getPlane( target ) {
  11417. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11418. }
  11419. /**
  11420. * Computes a barycentric coordinates from the given vector.
  11421. * Returns `null` if the triangle is degenerate.
  11422. *
  11423. * @param {Vector3} point - A point in 3D space.
  11424. * @param {Vector3} target - The target vector that is used to store the method's result.
  11425. * @return {?Vector3} The barycentric coordinates for the given point
  11426. */
  11427. getBarycoord( point, target ) {
  11428. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11429. }
  11430. /**
  11431. * Computes the value barycentrically interpolated for the given point on the
  11432. * triangle. Returns `null` if the triangle is degenerate.
  11433. *
  11434. * @param {Vector3} point - Position of interpolated point.
  11435. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11436. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11437. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11438. * @param {Vector3} target - The target vector that is used to store the method's result.
  11439. * @return {?Vector3} The interpolated value.
  11440. */
  11441. getInterpolation( point, v1, v2, v3, target ) {
  11442. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11443. }
  11444. /**
  11445. * Returns `true` if the given point, when projected onto the plane of the
  11446. * triangle, lies within the triangle.
  11447. *
  11448. * @param {Vector3} point - The point in 3D space to test.
  11449. * @return {boolean} Whether the given point, when projected onto the plane of the
  11450. * triangle, lies within the triangle or not.
  11451. */
  11452. containsPoint( point ) {
  11453. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11454. }
  11455. /**
  11456. * Returns `true` if the triangle is oriented towards the given direction.
  11457. *
  11458. * @param {Vector3} direction - The (normalized) direction vector.
  11459. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11460. */
  11461. isFrontFacing( direction ) {
  11462. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11463. }
  11464. /**
  11465. * Returns `true` if this triangle intersects with the given box.
  11466. *
  11467. * @param {Box3} box - The box to intersect.
  11468. * @return {boolean} Whether this triangle intersects with the given box or not.
  11469. */
  11470. intersectsBox( box ) {
  11471. return box.intersectsTriangle( this );
  11472. }
  11473. /**
  11474. * Returns the closest point on the triangle to the given point.
  11475. *
  11476. * @param {Vector3} p - The point to compute the closest point for.
  11477. * @param {Vector3} target - The target vector that is used to store the method's result.
  11478. * @return {Vector3} The closest point on the triangle.
  11479. */
  11480. closestPointToPoint( p, target ) {
  11481. const a = this.a, b = this.b, c = this.c;
  11482. let v, w;
  11483. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11484. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11485. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11486. // basically, we're distinguishing which of the voronoi regions of the triangle
  11487. // the point lies in with the minimum amount of redundant computation.
  11488. _vab.subVectors( b, a );
  11489. _vac.subVectors( c, a );
  11490. _vap.subVectors( p, a );
  11491. const d1 = _vab.dot( _vap );
  11492. const d2 = _vac.dot( _vap );
  11493. if ( d1 <= 0 && d2 <= 0 ) {
  11494. // vertex region of A; barycentric coords (1, 0, 0)
  11495. return target.copy( a );
  11496. }
  11497. _vbp.subVectors( p, b );
  11498. const d3 = _vab.dot( _vbp );
  11499. const d4 = _vac.dot( _vbp );
  11500. if ( d3 >= 0 && d4 <= d3 ) {
  11501. // vertex region of B; barycentric coords (0, 1, 0)
  11502. return target.copy( b );
  11503. }
  11504. const vc = d1 * d4 - d3 * d2;
  11505. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11506. v = d1 / ( d1 - d3 );
  11507. // edge region of AB; barycentric coords (1-v, v, 0)
  11508. return target.copy( a ).addScaledVector( _vab, v );
  11509. }
  11510. _vcp.subVectors( p, c );
  11511. const d5 = _vab.dot( _vcp );
  11512. const d6 = _vac.dot( _vcp );
  11513. if ( d6 >= 0 && d5 <= d6 ) {
  11514. // vertex region of C; barycentric coords (0, 0, 1)
  11515. return target.copy( c );
  11516. }
  11517. const vb = d5 * d2 - d1 * d6;
  11518. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11519. w = d2 / ( d2 - d6 );
  11520. // edge region of AC; barycentric coords (1-w, 0, w)
  11521. return target.copy( a ).addScaledVector( _vac, w );
  11522. }
  11523. const va = d3 * d6 - d5 * d4;
  11524. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11525. _vbc.subVectors( c, b );
  11526. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11527. // edge region of BC; barycentric coords (0, 1-w, w)
  11528. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11529. }
  11530. // face region
  11531. const denom = 1 / ( va + vb + vc );
  11532. // u = va * denom
  11533. v = vb * denom;
  11534. w = vc * denom;
  11535. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11536. }
  11537. /**
  11538. * Returns `true` if this triangle is equal with the given one.
  11539. *
  11540. * @param {Triangle} triangle - The triangle to test for equality.
  11541. * @return {boolean} Whether this triangle is equal with the given one.
  11542. */
  11543. equals( triangle ) {
  11544. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11545. }
  11546. }
  11547. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11548. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11549. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11550. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11551. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11552. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11553. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11554. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11555. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11556. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11557. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11558. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11559. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11560. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11561. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11562. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11563. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11564. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11565. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11566. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11567. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11568. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11569. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11570. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11571. const _hslA = { h: 0, s: 0, l: 0 };
  11572. const _hslB = { h: 0, s: 0, l: 0 };
  11573. function hue2rgb( p, q, t ) {
  11574. if ( t < 0 ) t += 1;
  11575. if ( t > 1 ) t -= 1;
  11576. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11577. if ( t < 1 / 2 ) return q;
  11578. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11579. return p;
  11580. }
  11581. /**
  11582. * A Color instance is represented by RGB components in the linear <i>working
  11583. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11584. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11585. * strings) are converted to the working color space automatically.
  11586. *
  11587. * ```js
  11588. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11589. * const color = new THREE.Color().setHex( 0x112233 );
  11590. * ```
  11591. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11592. * ```js
  11593. * // assumed already LinearSRGBColorSpace; no conversion
  11594. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11595. *
  11596. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11597. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11598. * ```
  11599. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11600. * see <i>Color management</i>. Iterating through a Color instance will yield
  11601. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11602. * in any of the following ways:
  11603. * ```js
  11604. * //empty constructor - will default white
  11605. * const color1 = new THREE.Color();
  11606. *
  11607. * //Hexadecimal color (recommended)
  11608. * const color2 = new THREE.Color( 0xff0000 );
  11609. *
  11610. * //RGB string
  11611. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11612. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11613. *
  11614. * //X11 color name - all 140 color names are supported.
  11615. * //Note the lack of CamelCase in the name
  11616. * const color5 = new THREE.Color( 'skyblue' );
  11617. * //HSL string
  11618. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11619. *
  11620. * //Separate RGB values between 0 and 1
  11621. * const color7 = new THREE.Color( 1, 0, 0 );
  11622. * ```
  11623. */
  11624. class Color {
  11625. /**
  11626. * Constructs a new color.
  11627. *
  11628. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11629. * and that method is used throughout the rest of the documentation.
  11630. *
  11631. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11632. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11633. * @param {number} [g] - The green component.
  11634. * @param {number} [b] - The blue component.
  11635. */
  11636. constructor( r, g, b ) {
  11637. /**
  11638. * This flag can be used for type testing.
  11639. *
  11640. * @type {boolean}
  11641. * @readonly
  11642. * @default true
  11643. */
  11644. this.isColor = true;
  11645. /**
  11646. * The red component.
  11647. *
  11648. * @type {number}
  11649. * @default 1
  11650. */
  11651. this.r = 1;
  11652. /**
  11653. * The green component.
  11654. *
  11655. * @type {number}
  11656. * @default 1
  11657. */
  11658. this.g = 1;
  11659. /**
  11660. * The blue component.
  11661. *
  11662. * @type {number}
  11663. * @default 1
  11664. */
  11665. this.b = 1;
  11666. return this.set( r, g, b );
  11667. }
  11668. /**
  11669. * Sets the colors's components from the given values.
  11670. *
  11671. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11672. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11673. * @param {number} [g] - The green component.
  11674. * @param {number} [b] - The blue component.
  11675. * @return {Color} A reference to this color.
  11676. */
  11677. set( r, g, b ) {
  11678. if ( g === undefined && b === undefined ) {
  11679. // r is THREE.Color, hex or string
  11680. const value = r;
  11681. if ( value && value.isColor ) {
  11682. this.copy( value );
  11683. } else if ( typeof value === 'number' ) {
  11684. this.setHex( value );
  11685. } else if ( typeof value === 'string' ) {
  11686. this.setStyle( value );
  11687. }
  11688. } else {
  11689. this.setRGB( r, g, b );
  11690. }
  11691. return this;
  11692. }
  11693. /**
  11694. * Sets the colors's components to the given scalar value.
  11695. *
  11696. * @param {number} scalar - The scalar value.
  11697. * @return {Color} A reference to this color.
  11698. */
  11699. setScalar( scalar ) {
  11700. this.r = scalar;
  11701. this.g = scalar;
  11702. this.b = scalar;
  11703. return this;
  11704. }
  11705. /**
  11706. * Sets this color from a hexadecimal value.
  11707. *
  11708. * @param {number} hex - The hexadecimal value.
  11709. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11710. * @return {Color} A reference to this color.
  11711. */
  11712. setHex( hex, colorSpace = SRGBColorSpace ) {
  11713. hex = Math.floor( hex );
  11714. this.r = ( hex >> 16 & 255 ) / 255;
  11715. this.g = ( hex >> 8 & 255 ) / 255;
  11716. this.b = ( hex & 255 ) / 255;
  11717. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11718. return this;
  11719. }
  11720. /**
  11721. * Sets this color from RGB values.
  11722. *
  11723. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11724. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11725. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11726. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11727. * @return {Color} A reference to this color.
  11728. */
  11729. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11730. this.r = r;
  11731. this.g = g;
  11732. this.b = b;
  11733. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11734. return this;
  11735. }
  11736. /**
  11737. * Sets this color from RGB values.
  11738. *
  11739. * @param {number} h - Hue value between `0.0` and `1.0`.
  11740. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11741. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11742. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11743. * @return {Color} A reference to this color.
  11744. */
  11745. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11746. // h,s,l ranges are in 0.0 - 1.0
  11747. h = euclideanModulo( h, 1 );
  11748. s = clamp( s, 0, 1 );
  11749. l = clamp( l, 0, 1 );
  11750. if ( s === 0 ) {
  11751. this.r = this.g = this.b = l;
  11752. } else {
  11753. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11754. const q = ( 2 * l ) - p;
  11755. this.r = hue2rgb( q, p, h + 1 / 3 );
  11756. this.g = hue2rgb( q, p, h );
  11757. this.b = hue2rgb( q, p, h - 1 / 3 );
  11758. }
  11759. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11760. return this;
  11761. }
  11762. /**
  11763. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11764. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11765. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  11766. * all 140 color names are supported).
  11767. *
  11768. * @param {string} style - Color as a CSS-style string.
  11769. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11770. * @return {Color} A reference to this color.
  11771. */
  11772. setStyle( style, colorSpace = SRGBColorSpace ) {
  11773. function handleAlpha( string ) {
  11774. if ( string === undefined ) return;
  11775. if ( parseFloat( string ) < 1 ) {
  11776. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  11777. }
  11778. }
  11779. let m;
  11780. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11781. // rgb / hsl
  11782. let color;
  11783. const name = m[ 1 ];
  11784. const components = m[ 2 ];
  11785. switch ( name ) {
  11786. case 'rgb':
  11787. case 'rgba':
  11788. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11789. // rgb(255,0,0) rgba(255,0,0,0.5)
  11790. handleAlpha( color[ 4 ] );
  11791. return this.setRGB(
  11792. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11793. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11794. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11795. colorSpace
  11796. );
  11797. }
  11798. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11799. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11800. handleAlpha( color[ 4 ] );
  11801. return this.setRGB(
  11802. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11803. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11804. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11805. colorSpace
  11806. );
  11807. }
  11808. break;
  11809. case 'hsl':
  11810. case 'hsla':
  11811. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11812. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11813. handleAlpha( color[ 4 ] );
  11814. return this.setHSL(
  11815. parseFloat( color[ 1 ] ) / 360,
  11816. parseFloat( color[ 2 ] ) / 100,
  11817. parseFloat( color[ 3 ] ) / 100,
  11818. colorSpace
  11819. );
  11820. }
  11821. break;
  11822. default:
  11823. console.warn( 'THREE.Color: Unknown color model ' + style );
  11824. }
  11825. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11826. // hex color
  11827. const hex = m[ 1 ];
  11828. const size = hex.length;
  11829. if ( size === 3 ) {
  11830. // #ff0
  11831. return this.setRGB(
  11832. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11833. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11834. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11835. colorSpace
  11836. );
  11837. } else if ( size === 6 ) {
  11838. // #ff0000
  11839. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11840. } else {
  11841. console.warn( 'THREE.Color: Invalid hex color ' + style );
  11842. }
  11843. } else if ( style && style.length > 0 ) {
  11844. return this.setColorName( style, colorSpace );
  11845. }
  11846. return this;
  11847. }
  11848. /**
  11849. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11850. * you don't need the other CSS-style formats.
  11851. *
  11852. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11853. * ```js
  11854. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11855. * ```
  11856. *
  11857. * @param {string} style - The color name.
  11858. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11859. * @return {Color} A reference to this color.
  11860. */
  11861. setColorName( style, colorSpace = SRGBColorSpace ) {
  11862. // color keywords
  11863. const hex = _colorKeywords[ style.toLowerCase() ];
  11864. if ( hex !== undefined ) {
  11865. // red
  11866. this.setHex( hex, colorSpace );
  11867. } else {
  11868. // unknown color
  11869. console.warn( 'THREE.Color: Unknown color ' + style );
  11870. }
  11871. return this;
  11872. }
  11873. /**
  11874. * Returns a new color with copied values from this instance.
  11875. *
  11876. * @return {Color} A clone of this instance.
  11877. */
  11878. clone() {
  11879. return new this.constructor( this.r, this.g, this.b );
  11880. }
  11881. /**
  11882. * Copies the values of the given color to this instance.
  11883. *
  11884. * @param {Color} color - The color to copy.
  11885. * @return {Color} A reference to this color.
  11886. */
  11887. copy( color ) {
  11888. this.r = color.r;
  11889. this.g = color.g;
  11890. this.b = color.b;
  11891. return this;
  11892. }
  11893. /**
  11894. * Copies the given color into this color, and then converts this color from
  11895. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11896. *
  11897. * @param {Color} color - The color to copy/convert.
  11898. * @return {Color} A reference to this color.
  11899. */
  11900. copySRGBToLinear( color ) {
  11901. this.r = SRGBToLinear( color.r );
  11902. this.g = SRGBToLinear( color.g );
  11903. this.b = SRGBToLinear( color.b );
  11904. return this;
  11905. }
  11906. /**
  11907. * Copies the given color into this color, and then converts this color from
  11908. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11909. *
  11910. * @param {Color} color - The color to copy/convert.
  11911. * @return {Color} A reference to this color.
  11912. */
  11913. copyLinearToSRGB( color ) {
  11914. this.r = LinearToSRGB( color.r );
  11915. this.g = LinearToSRGB( color.g );
  11916. this.b = LinearToSRGB( color.b );
  11917. return this;
  11918. }
  11919. /**
  11920. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11921. *
  11922. * @return {Color} A reference to this color.
  11923. */
  11924. convertSRGBToLinear() {
  11925. this.copySRGBToLinear( this );
  11926. return this;
  11927. }
  11928. /**
  11929. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11930. *
  11931. * @return {Color} A reference to this color.
  11932. */
  11933. convertLinearToSRGB() {
  11934. this.copyLinearToSRGB( this );
  11935. return this;
  11936. }
  11937. /**
  11938. * Returns the hexadecimal value of this color.
  11939. *
  11940. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11941. * @return {number} The hexadecimal value.
  11942. */
  11943. getHex( colorSpace = SRGBColorSpace ) {
  11944. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11945. 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 ) );
  11946. }
  11947. /**
  11948. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  11949. *
  11950. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11951. * @return {string} The hexadecimal value as a string.
  11952. */
  11953. getHexString( colorSpace = SRGBColorSpace ) {
  11954. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  11955. }
  11956. /**
  11957. * Converts the colors RGB values into the HSL format and stores them into the
  11958. * given target object.
  11959. *
  11960. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  11961. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11962. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  11963. */
  11964. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  11965. // h,s,l ranges are in 0.0 - 1.0
  11966. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11967. const r = _color.r, g = _color.g, b = _color.b;
  11968. const max = Math.max( r, g, b );
  11969. const min = Math.min( r, g, b );
  11970. let hue, saturation;
  11971. const lightness = ( min + max ) / 2.0;
  11972. if ( min === max ) {
  11973. hue = 0;
  11974. saturation = 0;
  11975. } else {
  11976. const delta = max - min;
  11977. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  11978. switch ( max ) {
  11979. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  11980. case g: hue = ( b - r ) / delta + 2; break;
  11981. case b: hue = ( r - g ) / delta + 4; break;
  11982. }
  11983. hue /= 6;
  11984. }
  11985. target.h = hue;
  11986. target.s = saturation;
  11987. target.l = lightness;
  11988. return target;
  11989. }
  11990. /**
  11991. * Returns the RGB values of this color and stores them into the given target object.
  11992. *
  11993. * @param {Color} target - The target color that is used to store the method's result.
  11994. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11995. * @return {Color} The RGB representation of this color.
  11996. */
  11997. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  11998. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11999. target.r = _color.r;
  12000. target.g = _color.g;
  12001. target.b = _color.b;
  12002. return target;
  12003. }
  12004. /**
  12005. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12006. *
  12007. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12008. * @return {string} The CSS representation of this color.
  12009. */
  12010. getStyle( colorSpace = SRGBColorSpace ) {
  12011. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12012. const r = _color.r, g = _color.g, b = _color.b;
  12013. if ( colorSpace !== SRGBColorSpace ) {
  12014. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12015. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12016. }
  12017. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12018. }
  12019. /**
  12020. * Adds the given HSL values to this color's values.
  12021. * Internally, this converts the color's RGB values to HSL, adds HSL
  12022. * and then converts the color back to RGB.
  12023. *
  12024. * @param {number} h - Hue value between `0.0` and `1.0`.
  12025. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12026. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12027. * @return {Color} A reference to this color.
  12028. */
  12029. offsetHSL( h, s, l ) {
  12030. this.getHSL( _hslA );
  12031. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12032. }
  12033. /**
  12034. * Adds the RGB values of the given color to the RGB values of this color.
  12035. *
  12036. * @param {Color} color - The color to add.
  12037. * @return {Color} A reference to this color.
  12038. */
  12039. add( color ) {
  12040. this.r += color.r;
  12041. this.g += color.g;
  12042. this.b += color.b;
  12043. return this;
  12044. }
  12045. /**
  12046. * Adds the RGB values of the given colors and stores the result in this instance.
  12047. *
  12048. * @param {Color} color1 - The first color.
  12049. * @param {Color} color2 - The second color.
  12050. * @return {Color} A reference to this color.
  12051. */
  12052. addColors( color1, color2 ) {
  12053. this.r = color1.r + color2.r;
  12054. this.g = color1.g + color2.g;
  12055. this.b = color1.b + color2.b;
  12056. return this;
  12057. }
  12058. /**
  12059. * Adds the given scalar value to the RGB values of this color.
  12060. *
  12061. * @param {number} s - The scalar to add.
  12062. * @return {Color} A reference to this color.
  12063. */
  12064. addScalar( s ) {
  12065. this.r += s;
  12066. this.g += s;
  12067. this.b += s;
  12068. return this;
  12069. }
  12070. /**
  12071. * Subtracts the RGB values of the given color from the RGB values of this color.
  12072. *
  12073. * @param {Color} color - The color to subtract.
  12074. * @return {Color} A reference to this color.
  12075. */
  12076. sub( color ) {
  12077. this.r = Math.max( 0, this.r - color.r );
  12078. this.g = Math.max( 0, this.g - color.g );
  12079. this.b = Math.max( 0, this.b - color.b );
  12080. return this;
  12081. }
  12082. /**
  12083. * Multiplies the RGB values of the given color with the RGB values of this color.
  12084. *
  12085. * @param {Color} color - The color to multiply.
  12086. * @return {Color} A reference to this color.
  12087. */
  12088. multiply( color ) {
  12089. this.r *= color.r;
  12090. this.g *= color.g;
  12091. this.b *= color.b;
  12092. return this;
  12093. }
  12094. /**
  12095. * Multiplies the given scalar value with the RGB values of this color.
  12096. *
  12097. * @param {number} s - The scalar to multiply.
  12098. * @return {Color} A reference to this color.
  12099. */
  12100. multiplyScalar( s ) {
  12101. this.r *= s;
  12102. this.g *= s;
  12103. this.b *= s;
  12104. return this;
  12105. }
  12106. /**
  12107. * Linearly interpolates this color's RGB values toward the RGB values of the
  12108. * given color. The alpha argument can be thought of as the ratio between
  12109. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12110. *
  12111. * @param {Color} color - The color to converge on.
  12112. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12113. * @return {Color} A reference to this color.
  12114. */
  12115. lerp( color, alpha ) {
  12116. this.r += ( color.r - this.r ) * alpha;
  12117. this.g += ( color.g - this.g ) * alpha;
  12118. this.b += ( color.b - this.b ) * alpha;
  12119. return this;
  12120. }
  12121. /**
  12122. * Linearly interpolates between the given colors and stores the result in this instance.
  12123. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12124. * is the first and `1.0` is the second color.
  12125. *
  12126. * @param {Color} color1 - The first color.
  12127. * @param {Color} color2 - The second color.
  12128. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12129. * @return {Color} A reference to this color.
  12130. */
  12131. lerpColors( color1, color2, alpha ) {
  12132. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12133. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12134. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12135. return this;
  12136. }
  12137. /**
  12138. * Linearly interpolates this color's HSL values toward the HSL values of the
  12139. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12140. * from one color to the other, but instead going through all the hues in between
  12141. * those two colors. The alpha argument can be thought of as the ratio between
  12142. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12143. *
  12144. * @param {Color} color - The color to converge on.
  12145. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12146. * @return {Color} A reference to this color.
  12147. */
  12148. lerpHSL( color, alpha ) {
  12149. this.getHSL( _hslA );
  12150. color.getHSL( _hslB );
  12151. const h = lerp( _hslA.h, _hslB.h, alpha );
  12152. const s = lerp( _hslA.s, _hslB.s, alpha );
  12153. const l = lerp( _hslA.l, _hslB.l, alpha );
  12154. this.setHSL( h, s, l );
  12155. return this;
  12156. }
  12157. /**
  12158. * Sets the color's RGB components from the given 3D vector.
  12159. *
  12160. * @param {Vector3} v - The vector to set.
  12161. * @return {Color} A reference to this color.
  12162. */
  12163. setFromVector3( v ) {
  12164. this.r = v.x;
  12165. this.g = v.y;
  12166. this.b = v.z;
  12167. return this;
  12168. }
  12169. /**
  12170. * Transforms this color with the given 3x3 matrix.
  12171. *
  12172. * @param {Matrix3} m - The matrix.
  12173. * @return {Color} A reference to this color.
  12174. */
  12175. applyMatrix3( m ) {
  12176. const r = this.r, g = this.g, b = this.b;
  12177. const e = m.elements;
  12178. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12179. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12180. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12181. return this;
  12182. }
  12183. /**
  12184. * Returns `true` if this color is equal with the given one.
  12185. *
  12186. * @param {Color} c - The color to test for equality.
  12187. * @return {boolean} Whether this bounding color is equal with the given one.
  12188. */
  12189. equals( c ) {
  12190. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12191. }
  12192. /**
  12193. * Sets this color's RGB components from the given array.
  12194. *
  12195. * @param {Array<number>} array - An array holding the RGB values.
  12196. * @param {number} [offset=0] - The offset into the array.
  12197. * @return {Color} A reference to this color.
  12198. */
  12199. fromArray( array, offset = 0 ) {
  12200. this.r = array[ offset ];
  12201. this.g = array[ offset + 1 ];
  12202. this.b = array[ offset + 2 ];
  12203. return this;
  12204. }
  12205. /**
  12206. * Writes the RGB components of this color to the given array. If no array is provided,
  12207. * the method returns a new instance.
  12208. *
  12209. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12210. * @param {number} [offset=0] - Index of the first element in the array.
  12211. * @return {Array<number>} The color components.
  12212. */
  12213. toArray( array = [], offset = 0 ) {
  12214. array[ offset ] = this.r;
  12215. array[ offset + 1 ] = this.g;
  12216. array[ offset + 2 ] = this.b;
  12217. return array;
  12218. }
  12219. /**
  12220. * Sets the components of this color from the given buffer attribute.
  12221. *
  12222. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12223. * @param {number} index - The index into the attribute.
  12224. * @return {Color} A reference to this color.
  12225. */
  12226. fromBufferAttribute( attribute, index ) {
  12227. this.r = attribute.getX( index );
  12228. this.g = attribute.getY( index );
  12229. this.b = attribute.getZ( index );
  12230. return this;
  12231. }
  12232. /**
  12233. * This methods defines the serialization result of this class. Returns the color
  12234. * as a hexadecimal value.
  12235. *
  12236. * @return {number} The hexadecimal value.
  12237. */
  12238. toJSON() {
  12239. return this.getHex();
  12240. }
  12241. *[ Symbol.iterator ]() {
  12242. yield this.r;
  12243. yield this.g;
  12244. yield this.b;
  12245. }
  12246. }
  12247. const _color = /*@__PURE__*/ new Color();
  12248. /**
  12249. * A dictionary with X11 color names.
  12250. *
  12251. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12252. *
  12253. * @static
  12254. * @type {Object}
  12255. */
  12256. Color.NAMES = _colorKeywords;
  12257. let _materialId = 0;
  12258. /**
  12259. * Abstract base class for materials.
  12260. *
  12261. * Materials define the appearance of renderable 3D objects.
  12262. *
  12263. * @abstract
  12264. * @augments EventDispatcher
  12265. */
  12266. class Material extends EventDispatcher {
  12267. /**
  12268. * Constructs a new material.
  12269. */
  12270. constructor() {
  12271. super();
  12272. /**
  12273. * This flag can be used for type testing.
  12274. *
  12275. * @type {boolean}
  12276. * @readonly
  12277. * @default true
  12278. */
  12279. this.isMaterial = true;
  12280. /**
  12281. * The ID of the material.
  12282. *
  12283. * @name Material#id
  12284. * @type {number}
  12285. * @readonly
  12286. */
  12287. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12288. /**
  12289. * The UUID of the material.
  12290. *
  12291. * @type {string}
  12292. * @readonly
  12293. */
  12294. this.uuid = generateUUID();
  12295. /**
  12296. * The name of the material.
  12297. *
  12298. * @type {string}
  12299. */
  12300. this.name = '';
  12301. /**
  12302. * The type property is used for detecting the object type
  12303. * in context of serialization/deserialization.
  12304. *
  12305. * @type {string}
  12306. * @readonly
  12307. */
  12308. this.type = 'Material';
  12309. /**
  12310. * Defines the blending type of the material.
  12311. *
  12312. * It must be set to `CustomBlending` if custom blending properties like
  12313. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12314. * should have any effect.
  12315. *
  12316. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12317. * @default NormalBlending
  12318. */
  12319. this.blending = NormalBlending;
  12320. /**
  12321. * Defines which side of faces will be rendered - front, back or both.
  12322. *
  12323. * @type {(FrontSide|BackSide|DoubleSide)}
  12324. * @default FrontSide
  12325. */
  12326. this.side = FrontSide;
  12327. /**
  12328. * If set to `true`, vertex colors should be used.
  12329. *
  12330. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12331. * four (RGBA) component color buffer attribute is used.
  12332. *
  12333. * @type {boolean}
  12334. * @default false
  12335. */
  12336. this.vertexColors = false;
  12337. /**
  12338. * Defines how transparent the material is.
  12339. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12340. *
  12341. * If the {@link Material#transparent} is not set to `true`,
  12342. * the material will remain fully opaque and this value will only affect its color.
  12343. *
  12344. * @type {number}
  12345. * @default 1
  12346. */
  12347. this.opacity = 1;
  12348. /**
  12349. * Defines whether this material is transparent. This has an effect on
  12350. * rendering as transparent objects need special treatment and are rendered
  12351. * after non-transparent objects.
  12352. *
  12353. * When set to true, the extent to which the material is transparent is
  12354. * controlled by {@link Material#opacity}.
  12355. *
  12356. * @type {boolean}
  12357. * @default false
  12358. */
  12359. this.transparent = false;
  12360. /**
  12361. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12362. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12363. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12364. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12365. *
  12366. * @type {boolean}
  12367. * @default false
  12368. */
  12369. this.alphaHash = false;
  12370. /**
  12371. * Defines the blending source factor.
  12372. *
  12373. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12374. * @default SrcAlphaFactor
  12375. */
  12376. this.blendSrc = SrcAlphaFactor;
  12377. /**
  12378. * Defines the blending destination factor.
  12379. *
  12380. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12381. * @default OneMinusSrcAlphaFactor
  12382. */
  12383. this.blendDst = OneMinusSrcAlphaFactor;
  12384. /**
  12385. * Defines the blending equation.
  12386. *
  12387. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12388. * @default AddEquation
  12389. */
  12390. this.blendEquation = AddEquation;
  12391. /**
  12392. * Defines the blending source alpha factor.
  12393. *
  12394. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12395. * @default null
  12396. */
  12397. this.blendSrcAlpha = null;
  12398. /**
  12399. * Defines the blending destination alpha factor.
  12400. *
  12401. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12402. * @default null
  12403. */
  12404. this.blendDstAlpha = null;
  12405. /**
  12406. * Defines the blending equation of the alpha channel.
  12407. *
  12408. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12409. * @default null
  12410. */
  12411. this.blendEquationAlpha = null;
  12412. /**
  12413. * Represents the RGB values of the constant blend color.
  12414. *
  12415. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12416. *
  12417. * @type {Color}
  12418. * @default (0,0,0)
  12419. */
  12420. this.blendColor = new Color( 0, 0, 0 );
  12421. /**
  12422. * Represents the alpha value of the constant blend color.
  12423. *
  12424. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12425. *
  12426. * @type {number}
  12427. * @default 0
  12428. */
  12429. this.blendAlpha = 0;
  12430. /**
  12431. * Defines the depth function.
  12432. *
  12433. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12434. * @default LessEqualDepth
  12435. */
  12436. this.depthFunc = LessEqualDepth;
  12437. /**
  12438. * Whether to have depth test enabled when rendering this material.
  12439. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12440. *
  12441. * @type {boolean}
  12442. * @default true
  12443. */
  12444. this.depthTest = true;
  12445. /**
  12446. * Whether rendering this material has any effect on the depth buffer.
  12447. *
  12448. * When drawing 2D overlays it can be useful to disable the depth writing in
  12449. * order to layer several things together without creating z-index artifacts.
  12450. *
  12451. * @type {boolean}
  12452. * @default true
  12453. */
  12454. this.depthWrite = true;
  12455. /**
  12456. * The bit mask to use when writing to the stencil buffer.
  12457. *
  12458. * @type {number}
  12459. * @default 0xff
  12460. */
  12461. this.stencilWriteMask = 0xff;
  12462. /**
  12463. * The stencil comparison function to use.
  12464. *
  12465. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12466. * @default AlwaysStencilFunc
  12467. */
  12468. this.stencilFunc = AlwaysStencilFunc;
  12469. /**
  12470. * The value to use when performing stencil comparisons or stencil operations.
  12471. *
  12472. * @type {number}
  12473. * @default 0
  12474. */
  12475. this.stencilRef = 0;
  12476. /**
  12477. * The bit mask to use when comparing against the stencil buffer.
  12478. *
  12479. * @type {number}
  12480. * @default 0xff
  12481. */
  12482. this.stencilFuncMask = 0xff;
  12483. /**
  12484. * Which stencil operation to perform when the comparison function returns `false`.
  12485. *
  12486. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12487. * @default KeepStencilOp
  12488. */
  12489. this.stencilFail = KeepStencilOp;
  12490. /**
  12491. * Which stencil operation to perform when the comparison function returns
  12492. * `true` but the depth test fails.
  12493. *
  12494. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12495. * @default KeepStencilOp
  12496. */
  12497. this.stencilZFail = KeepStencilOp;
  12498. /**
  12499. * Which stencil operation to perform when the comparison function returns
  12500. * `true` and the depth test passes.
  12501. *
  12502. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12503. * @default KeepStencilOp
  12504. */
  12505. this.stencilZPass = KeepStencilOp;
  12506. /**
  12507. * Whether stencil operations are performed against the stencil buffer. In
  12508. * order to perform writes or comparisons against the stencil buffer this
  12509. * value must be `true`.
  12510. *
  12511. * @type {boolean}
  12512. * @default false
  12513. */
  12514. this.stencilWrite = false;
  12515. /**
  12516. * User-defined clipping planes specified as THREE.Plane objects in world
  12517. * space. These planes apply to the objects this material is attached to.
  12518. * Points in space whose signed distance to the plane is negative are clipped
  12519. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12520. * be `true`.
  12521. *
  12522. * @type {?Array<Plane>}
  12523. * @default null
  12524. */
  12525. this.clippingPlanes = null;
  12526. /**
  12527. * Changes the behavior of clipping planes so that only their intersection is
  12528. * clipped, rather than their union.
  12529. *
  12530. * @type {boolean}
  12531. * @default false
  12532. */
  12533. this.clipIntersection = false;
  12534. /**
  12535. * Defines whether to clip shadows according to the clipping planes specified
  12536. * on this material.
  12537. *
  12538. * @type {boolean}
  12539. * @default false
  12540. */
  12541. this.clipShadows = false;
  12542. /**
  12543. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12544. * is determined as follows:
  12545. *
  12546. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12547. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12548. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12549. *
  12550. * @type {?(FrontSide|BackSide|DoubleSide)}
  12551. * @default null
  12552. */
  12553. this.shadowSide = null;
  12554. /**
  12555. * Whether to render the material's color.
  12556. *
  12557. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12558. * objects that occlude other objects.
  12559. *
  12560. * @type {boolean}
  12561. * @default true
  12562. */
  12563. this.colorWrite = true;
  12564. /**
  12565. * Override the renderer's default precision for this material.
  12566. *
  12567. * @type {?('highp'|'mediump'|'lowp')}
  12568. * @default null
  12569. */
  12570. this.precision = null;
  12571. /**
  12572. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12573. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12574. * The offset is added before the depth test is performed and before the value is written
  12575. * into the depth buffer.
  12576. *
  12577. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12578. * rendering solids with highlighted edges.
  12579. *
  12580. * @type {boolean}
  12581. * @default false
  12582. */
  12583. this.polygonOffset = false;
  12584. /**
  12585. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12586. *
  12587. * @type {number}
  12588. * @default 0
  12589. */
  12590. this.polygonOffsetFactor = 0;
  12591. /**
  12592. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12593. *
  12594. * @type {number}
  12595. * @default 0
  12596. */
  12597. this.polygonOffsetUnits = 0;
  12598. /**
  12599. * Whether to apply dithering to the color to remove the appearance of banding.
  12600. *
  12601. * @type {boolean}
  12602. * @default false
  12603. */
  12604. this.dithering = false;
  12605. /**
  12606. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12607. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12608. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12609. *
  12610. * @type {boolean}
  12611. * @default false
  12612. */
  12613. this.alphaToCoverage = false;
  12614. /**
  12615. * Whether to premultiply the alpha (transparency) value.
  12616. *
  12617. * @type {boolean}
  12618. * @default false
  12619. */
  12620. this.premultipliedAlpha = false;
  12621. /**
  12622. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12623. *
  12624. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12625. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12626. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12627. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12628. * disable the two pass rendering to avoid performance issues.
  12629. *
  12630. * @type {boolean}
  12631. * @default false
  12632. */
  12633. this.forceSinglePass = false;
  12634. /**
  12635. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12636. *
  12637. * @type {boolean}
  12638. * @default true
  12639. */
  12640. this.allowOverride = true;
  12641. /**
  12642. * Defines whether 3D objects using this material are visible.
  12643. *
  12644. * @type {boolean}
  12645. * @default true
  12646. */
  12647. this.visible = true;
  12648. /**
  12649. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12650. *
  12651. * It is ignored when rendering to a render target or using post processing or when using
  12652. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12653. *
  12654. * @type {boolean}
  12655. * @default true
  12656. */
  12657. this.toneMapped = true;
  12658. /**
  12659. * An object that can be used to store custom data about the Material. It
  12660. * should not hold references to functions as these will not be cloned.
  12661. *
  12662. * @type {Object}
  12663. */
  12664. this.userData = {};
  12665. /**
  12666. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12667. *
  12668. * @type {number}
  12669. * @readonly
  12670. * @default 0
  12671. */
  12672. this.version = 0;
  12673. this._alphaTest = 0;
  12674. }
  12675. /**
  12676. * Sets the alpha value to be used when running an alpha test. The material
  12677. * will not be rendered if the opacity is lower than this value.
  12678. *
  12679. * @type {number}
  12680. * @readonly
  12681. * @default 0
  12682. */
  12683. get alphaTest() {
  12684. return this._alphaTest;
  12685. }
  12686. set alphaTest( value ) {
  12687. if ( this._alphaTest > 0 !== value > 0 ) {
  12688. this.version ++;
  12689. }
  12690. this._alphaTest = value;
  12691. }
  12692. /**
  12693. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12694. *
  12695. * This method can only be used when rendering with {@link WebGLRenderer}.
  12696. *
  12697. * @param {WebGLRenderer} renderer - The renderer.
  12698. * @param {Scene} scene - The scene.
  12699. * @param {Camera} camera - The camera that is used to render the scene.
  12700. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12701. * @param {Object3D} object - The 3D object.
  12702. * @param {Object} group - The geometry group data.
  12703. */
  12704. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12705. /**
  12706. * An optional callback that is executed immediately before the shader
  12707. * program is compiled. This function is called with the shader source code
  12708. * as a parameter. Useful for the modification of built-in materials.
  12709. *
  12710. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12711. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12712. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  12713. *
  12714. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12715. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12716. */
  12717. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12718. /**
  12719. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12720. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12721. * shader or recompile the shader for this material as needed.
  12722. *
  12723. * This method can only be used when rendering with {@link WebGLRenderer}.
  12724. *
  12725. * @return {string} The custom program cache key.
  12726. */
  12727. customProgramCacheKey() {
  12728. return this.onBeforeCompile.toString();
  12729. }
  12730. /**
  12731. * This method can be used to set default values from parameter objects.
  12732. * It is a generic implementation so it can be used with different types
  12733. * of materials.
  12734. *
  12735. * @param {Object} [values] - The material values to set.
  12736. */
  12737. setValues( values ) {
  12738. if ( values === undefined ) return;
  12739. for ( const key in values ) {
  12740. const newValue = values[ key ];
  12741. if ( newValue === undefined ) {
  12742. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  12743. continue;
  12744. }
  12745. const currentValue = this[ key ];
  12746. if ( currentValue === undefined ) {
  12747. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12748. continue;
  12749. }
  12750. if ( currentValue && currentValue.isColor ) {
  12751. currentValue.set( newValue );
  12752. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12753. currentValue.copy( newValue );
  12754. } else {
  12755. this[ key ] = newValue;
  12756. }
  12757. }
  12758. }
  12759. /**
  12760. * Serializes the material into JSON.
  12761. *
  12762. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12763. * @return {Object} A JSON object representing the serialized material.
  12764. * @see {@link ObjectLoader#parse}
  12765. */
  12766. toJSON( meta ) {
  12767. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12768. if ( isRootObject ) {
  12769. meta = {
  12770. textures: {},
  12771. images: {}
  12772. };
  12773. }
  12774. const data = {
  12775. metadata: {
  12776. version: 4.7,
  12777. type: 'Material',
  12778. generator: 'Material.toJSON'
  12779. }
  12780. };
  12781. // standard Material serialization
  12782. data.uuid = this.uuid;
  12783. data.type = this.type;
  12784. if ( this.name !== '' ) data.name = this.name;
  12785. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12786. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12787. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12788. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12789. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12790. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12791. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12792. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12793. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12794. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12795. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12796. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12797. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12798. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12799. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12800. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12801. }
  12802. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12803. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12804. }
  12805. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12806. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12807. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12808. }
  12809. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  12810. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  12811. }
  12812. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  12813. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  12814. }
  12815. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12816. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12817. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12818. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12819. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12820. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12821. }
  12822. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12823. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12824. }
  12825. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12826. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12827. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12828. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12829. }
  12830. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12831. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12832. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12833. if ( this.lightMap && this.lightMap.isTexture ) {
  12834. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12835. data.lightMapIntensity = this.lightMapIntensity;
  12836. }
  12837. if ( this.aoMap && this.aoMap.isTexture ) {
  12838. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12839. data.aoMapIntensity = this.aoMapIntensity;
  12840. }
  12841. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12842. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12843. data.bumpScale = this.bumpScale;
  12844. }
  12845. if ( this.normalMap && this.normalMap.isTexture ) {
  12846. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12847. data.normalMapType = this.normalMapType;
  12848. data.normalScale = this.normalScale.toArray();
  12849. }
  12850. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12851. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12852. data.displacementScale = this.displacementScale;
  12853. data.displacementBias = this.displacementBias;
  12854. }
  12855. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12856. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12857. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12858. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12859. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12860. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12861. if ( this.envMap && this.envMap.isTexture ) {
  12862. data.envMap = this.envMap.toJSON( meta ).uuid;
  12863. if ( this.combine !== undefined ) data.combine = this.combine;
  12864. }
  12865. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12866. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12867. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12868. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12869. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12870. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12871. }
  12872. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12873. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12874. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12875. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12876. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12877. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12878. if ( this.size !== undefined ) data.size = this.size;
  12879. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12880. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12881. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12882. if ( this.side !== FrontSide ) data.side = this.side;
  12883. if ( this.vertexColors === true ) data.vertexColors = true;
  12884. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12885. if ( this.transparent === true ) data.transparent = true;
  12886. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12887. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12888. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12889. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12890. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12891. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12892. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12893. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12894. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12895. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12896. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12897. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12898. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12899. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12900. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12901. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12902. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12903. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12904. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12905. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12906. // rotation (SpriteMaterial)
  12907. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12908. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12909. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12910. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12911. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12912. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12913. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12914. if ( this.scale !== undefined ) data.scale = this.scale;
  12915. if ( this.dithering === true ) data.dithering = true;
  12916. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12917. if ( this.alphaHash === true ) data.alphaHash = true;
  12918. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12919. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12920. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12921. if ( this.wireframe === true ) data.wireframe = true;
  12922. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12923. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12924. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12925. if ( this.flatShading === true ) data.flatShading = true;
  12926. if ( this.visible === false ) data.visible = false;
  12927. if ( this.toneMapped === false ) data.toneMapped = false;
  12928. if ( this.fog === false ) data.fog = false;
  12929. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12930. // TODO: Copied from Object3D.toJSON
  12931. function extractFromCache( cache ) {
  12932. const values = [];
  12933. for ( const key in cache ) {
  12934. const data = cache[ key ];
  12935. delete data.metadata;
  12936. values.push( data );
  12937. }
  12938. return values;
  12939. }
  12940. if ( isRootObject ) {
  12941. const textures = extractFromCache( meta.textures );
  12942. const images = extractFromCache( meta.images );
  12943. if ( textures.length > 0 ) data.textures = textures;
  12944. if ( images.length > 0 ) data.images = images;
  12945. }
  12946. return data;
  12947. }
  12948. /**
  12949. * Returns a new material with copied values from this instance.
  12950. *
  12951. * @return {Material} A clone of this instance.
  12952. */
  12953. clone() {
  12954. return new this.constructor().copy( this );
  12955. }
  12956. /**
  12957. * Copies the values of the given material to this instance.
  12958. *
  12959. * @param {Material} source - The material to copy.
  12960. * @return {Material} A reference to this instance.
  12961. */
  12962. copy( source ) {
  12963. this.name = source.name;
  12964. this.blending = source.blending;
  12965. this.side = source.side;
  12966. this.vertexColors = source.vertexColors;
  12967. this.opacity = source.opacity;
  12968. this.transparent = source.transparent;
  12969. this.blendSrc = source.blendSrc;
  12970. this.blendDst = source.blendDst;
  12971. this.blendEquation = source.blendEquation;
  12972. this.blendSrcAlpha = source.blendSrcAlpha;
  12973. this.blendDstAlpha = source.blendDstAlpha;
  12974. this.blendEquationAlpha = source.blendEquationAlpha;
  12975. this.blendColor.copy( source.blendColor );
  12976. this.blendAlpha = source.blendAlpha;
  12977. this.depthFunc = source.depthFunc;
  12978. this.depthTest = source.depthTest;
  12979. this.depthWrite = source.depthWrite;
  12980. this.stencilWriteMask = source.stencilWriteMask;
  12981. this.stencilFunc = source.stencilFunc;
  12982. this.stencilRef = source.stencilRef;
  12983. this.stencilFuncMask = source.stencilFuncMask;
  12984. this.stencilFail = source.stencilFail;
  12985. this.stencilZFail = source.stencilZFail;
  12986. this.stencilZPass = source.stencilZPass;
  12987. this.stencilWrite = source.stencilWrite;
  12988. const srcPlanes = source.clippingPlanes;
  12989. let dstPlanes = null;
  12990. if ( srcPlanes !== null ) {
  12991. const n = srcPlanes.length;
  12992. dstPlanes = new Array( n );
  12993. for ( let i = 0; i !== n; ++ i ) {
  12994. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12995. }
  12996. }
  12997. this.clippingPlanes = dstPlanes;
  12998. this.clipIntersection = source.clipIntersection;
  12999. this.clipShadows = source.clipShadows;
  13000. this.shadowSide = source.shadowSide;
  13001. this.colorWrite = source.colorWrite;
  13002. this.precision = source.precision;
  13003. this.polygonOffset = source.polygonOffset;
  13004. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13005. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13006. this.dithering = source.dithering;
  13007. this.alphaTest = source.alphaTest;
  13008. this.alphaHash = source.alphaHash;
  13009. this.alphaToCoverage = source.alphaToCoverage;
  13010. this.premultipliedAlpha = source.premultipliedAlpha;
  13011. this.forceSinglePass = source.forceSinglePass;
  13012. this.visible = source.visible;
  13013. this.toneMapped = source.toneMapped;
  13014. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13015. return this;
  13016. }
  13017. /**
  13018. * Frees the GPU-related resources allocated by this instance. Call this
  13019. * method whenever this instance is no longer used in your app.
  13020. *
  13021. * @fires Material#dispose
  13022. */
  13023. dispose() {
  13024. /**
  13025. * Fires when the material has been disposed of.
  13026. *
  13027. * @event Material#dispose
  13028. * @type {Object}
  13029. */
  13030. this.dispatchEvent( { type: 'dispose' } );
  13031. }
  13032. /**
  13033. * Setting this property to `true` indicates the engine the material
  13034. * needs to be recompiled.
  13035. *
  13036. * @type {boolean}
  13037. * @default false
  13038. * @param {boolean} value
  13039. */
  13040. set needsUpdate( value ) {
  13041. if ( value === true ) this.version ++;
  13042. }
  13043. }
  13044. /**
  13045. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13046. *
  13047. * This material is not affected by lights.
  13048. *
  13049. * @augments Material
  13050. */
  13051. class MeshBasicMaterial extends Material {
  13052. /**
  13053. * Constructs a new mesh basic material.
  13054. *
  13055. * @param {Object} [parameters] - An object with one or more properties
  13056. * defining the material's appearance. Any property of the material
  13057. * (including any property from inherited materials) can be passed
  13058. * in here. Color values can be passed any type of value accepted
  13059. * by {@link Color#set}.
  13060. */
  13061. constructor( parameters ) {
  13062. super();
  13063. /**
  13064. * This flag can be used for type testing.
  13065. *
  13066. * @type {boolean}
  13067. * @readonly
  13068. * @default true
  13069. */
  13070. this.isMeshBasicMaterial = true;
  13071. this.type = 'MeshBasicMaterial';
  13072. /**
  13073. * Color of the material.
  13074. *
  13075. * @type {Color}
  13076. * @default (1,1,1)
  13077. */
  13078. this.color = new Color( 0xffffff ); // diffuse
  13079. /**
  13080. * The color map. May optionally include an alpha channel, typically combined
  13081. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13082. * color is modulated by the diffuse `color`.
  13083. *
  13084. * @type {?Texture}
  13085. * @default null
  13086. */
  13087. this.map = null;
  13088. /**
  13089. * The light map. Requires a second set of UVs.
  13090. *
  13091. * @type {?Texture}
  13092. * @default null
  13093. */
  13094. this.lightMap = null;
  13095. /**
  13096. * Intensity of the baked light.
  13097. *
  13098. * @type {number}
  13099. * @default 1
  13100. */
  13101. this.lightMapIntensity = 1.0;
  13102. /**
  13103. * The red channel of this texture is used as the ambient occlusion map.
  13104. * Requires a second set of UVs.
  13105. *
  13106. * @type {?Texture}
  13107. * @default null
  13108. */
  13109. this.aoMap = null;
  13110. /**
  13111. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13112. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13113. * red channel is also `1`, ambient light is fully occluded on a surface.
  13114. *
  13115. * @type {number}
  13116. * @default 1
  13117. */
  13118. this.aoMapIntensity = 1.0;
  13119. /**
  13120. * Specular map used by the material.
  13121. *
  13122. * @type {?Texture}
  13123. * @default null
  13124. */
  13125. this.specularMap = null;
  13126. /**
  13127. * The alpha map is a grayscale texture that controls the opacity across the
  13128. * surface (black: fully transparent; white: fully opaque).
  13129. *
  13130. * Only the color of the texture is used, ignoring the alpha channel if one
  13131. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13132. * when sampling this texture due to the extra bit of precision provided for
  13133. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13134. * luminance/alpha textures will also still work as expected.
  13135. *
  13136. * @type {?Texture}
  13137. * @default null
  13138. */
  13139. this.alphaMap = null;
  13140. /**
  13141. * The environment map.
  13142. *
  13143. * @type {?Texture}
  13144. * @default null
  13145. */
  13146. this.envMap = null;
  13147. /**
  13148. * The rotation of the environment map in radians.
  13149. *
  13150. * @type {Euler}
  13151. * @default (0,0,0)
  13152. */
  13153. this.envMapRotation = new Euler();
  13154. /**
  13155. * How to combine the result of the surface's color with the environment map, if any.
  13156. *
  13157. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13158. * blend between the two colors.
  13159. *
  13160. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13161. * @default MultiplyOperation
  13162. */
  13163. this.combine = MultiplyOperation;
  13164. /**
  13165. * How much the environment map affects the surface.
  13166. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13167. *
  13168. * @type {number}
  13169. * @default 1
  13170. */
  13171. this.reflectivity = 1;
  13172. /**
  13173. * The index of refraction (IOR) of air (approximately 1) divided by the
  13174. * index of refraction of the material. It is used with environment mapping
  13175. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13176. * The refraction ratio should not exceed `1`.
  13177. *
  13178. * @type {number}
  13179. * @default 0.98
  13180. */
  13181. this.refractionRatio = 0.98;
  13182. /**
  13183. * Renders the geometry as a wireframe.
  13184. *
  13185. * @type {boolean}
  13186. * @default false
  13187. */
  13188. this.wireframe = false;
  13189. /**
  13190. * Controls the thickness of the wireframe.
  13191. *
  13192. * Can only be used with {@link SVGRenderer}.
  13193. *
  13194. * @type {number}
  13195. * @default 1
  13196. */
  13197. this.wireframeLinewidth = 1;
  13198. /**
  13199. * Defines appearance of wireframe ends.
  13200. *
  13201. * Can only be used with {@link SVGRenderer}.
  13202. *
  13203. * @type {('round'|'bevel'|'miter')}
  13204. * @default 'round'
  13205. */
  13206. this.wireframeLinecap = 'round';
  13207. /**
  13208. * Defines appearance of wireframe joints.
  13209. *
  13210. * Can only be used with {@link SVGRenderer}.
  13211. *
  13212. * @type {('round'|'bevel'|'miter')}
  13213. * @default 'round'
  13214. */
  13215. this.wireframeLinejoin = 'round';
  13216. /**
  13217. * Whether the material is affected by fog or not.
  13218. *
  13219. * @type {boolean}
  13220. * @default true
  13221. */
  13222. this.fog = true;
  13223. this.setValues( parameters );
  13224. }
  13225. copy( source ) {
  13226. super.copy( source );
  13227. this.color.copy( source.color );
  13228. this.map = source.map;
  13229. this.lightMap = source.lightMap;
  13230. this.lightMapIntensity = source.lightMapIntensity;
  13231. this.aoMap = source.aoMap;
  13232. this.aoMapIntensity = source.aoMapIntensity;
  13233. this.specularMap = source.specularMap;
  13234. this.alphaMap = source.alphaMap;
  13235. this.envMap = source.envMap;
  13236. this.envMapRotation.copy( source.envMapRotation );
  13237. this.combine = source.combine;
  13238. this.reflectivity = source.reflectivity;
  13239. this.refractionRatio = source.refractionRatio;
  13240. this.wireframe = source.wireframe;
  13241. this.wireframeLinewidth = source.wireframeLinewidth;
  13242. this.wireframeLinecap = source.wireframeLinecap;
  13243. this.wireframeLinejoin = source.wireframeLinejoin;
  13244. this.fog = source.fog;
  13245. return this;
  13246. }
  13247. }
  13248. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13249. const _tables = /*@__PURE__*/ _generateTables();
  13250. function _generateTables() {
  13251. // float32 to float16 helpers
  13252. const buffer = new ArrayBuffer( 4 );
  13253. const floatView = new Float32Array( buffer );
  13254. const uint32View = new Uint32Array( buffer );
  13255. const baseTable = new Uint32Array( 512 );
  13256. const shiftTable = new Uint32Array( 512 );
  13257. for ( let i = 0; i < 256; ++ i ) {
  13258. const e = i - 127;
  13259. // very small number (0, -0)
  13260. if ( e < -27 ) {
  13261. baseTable[ i ] = 0x0000;
  13262. baseTable[ i | 0x100 ] = 0x8000;
  13263. shiftTable[ i ] = 24;
  13264. shiftTable[ i | 0x100 ] = 24;
  13265. // small number (denorm)
  13266. } else if ( e < -14 ) {
  13267. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13268. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13269. shiftTable[ i ] = - e - 1;
  13270. shiftTable[ i | 0x100 ] = - e - 1;
  13271. // normal number
  13272. } else if ( e <= 15 ) {
  13273. baseTable[ i ] = ( e + 15 ) << 10;
  13274. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13275. shiftTable[ i ] = 13;
  13276. shiftTable[ i | 0x100 ] = 13;
  13277. // large number (Infinity, -Infinity)
  13278. } else if ( e < 128 ) {
  13279. baseTable[ i ] = 0x7c00;
  13280. baseTable[ i | 0x100 ] = 0xfc00;
  13281. shiftTable[ i ] = 24;
  13282. shiftTable[ i | 0x100 ] = 24;
  13283. // stay (NaN, Infinity, -Infinity)
  13284. } else {
  13285. baseTable[ i ] = 0x7c00;
  13286. baseTable[ i | 0x100 ] = 0xfc00;
  13287. shiftTable[ i ] = 13;
  13288. shiftTable[ i | 0x100 ] = 13;
  13289. }
  13290. }
  13291. // float16 to float32 helpers
  13292. const mantissaTable = new Uint32Array( 2048 );
  13293. const exponentTable = new Uint32Array( 64 );
  13294. const offsetTable = new Uint32Array( 64 );
  13295. for ( let i = 1; i < 1024; ++ i ) {
  13296. let m = i << 13; // zero pad mantissa bits
  13297. let e = 0; // zero exponent
  13298. // normalized
  13299. while ( ( m & 0x00800000 ) === 0 ) {
  13300. m <<= 1;
  13301. e -= 0x00800000; // decrement exponent
  13302. }
  13303. m &= -8388609; // clear leading 1 bit
  13304. e += 0x38800000; // adjust bias
  13305. mantissaTable[ i ] = m | e;
  13306. }
  13307. for ( let i = 1024; i < 2048; ++ i ) {
  13308. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13309. }
  13310. for ( let i = 1; i < 31; ++ i ) {
  13311. exponentTable[ i ] = i << 23;
  13312. }
  13313. exponentTable[ 31 ] = 0x47800000;
  13314. exponentTable[ 32 ] = 0x80000000;
  13315. for ( let i = 33; i < 63; ++ i ) {
  13316. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13317. }
  13318. exponentTable[ 63 ] = 0xc7800000;
  13319. for ( let i = 1; i < 64; ++ i ) {
  13320. if ( i !== 32 ) {
  13321. offsetTable[ i ] = 1024;
  13322. }
  13323. }
  13324. return {
  13325. floatView: floatView,
  13326. uint32View: uint32View,
  13327. baseTable: baseTable,
  13328. shiftTable: shiftTable,
  13329. mantissaTable: mantissaTable,
  13330. exponentTable: exponentTable,
  13331. offsetTable: offsetTable
  13332. };
  13333. }
  13334. /**
  13335. * Returns a half precision floating point value (FP16) from the given single
  13336. * precision floating point value (FP32).
  13337. *
  13338. * @param {number} val - A single precision floating point value.
  13339. * @return {number} The FP16 value.
  13340. */
  13341. function toHalfFloat( val ) {
  13342. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  13343. val = clamp( val, -65504, 65504 );
  13344. _tables.floatView[ 0 ] = val;
  13345. const f = _tables.uint32View[ 0 ];
  13346. const e = ( f >> 23 ) & 0x1ff;
  13347. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13348. }
  13349. /**
  13350. * Returns a single precision floating point value (FP32) from the given half
  13351. * precision floating point value (FP16).
  13352. *
  13353. * @param {number} val - A half precision floating point value.
  13354. * @return {number} The FP32 value.
  13355. */
  13356. function fromHalfFloat( val ) {
  13357. const m = val >> 10;
  13358. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13359. return _tables.floatView[ 0 ];
  13360. }
  13361. /**
  13362. * A class containing utility functions for data.
  13363. *
  13364. * @hideconstructor
  13365. */
  13366. class DataUtils {
  13367. /**
  13368. * Returns a half precision floating point value (FP16) from the given single
  13369. * precision floating point value (FP32).
  13370. *
  13371. * @param {number} val - A single precision floating point value.
  13372. * @return {number} The FP16 value.
  13373. */
  13374. static toHalfFloat( val ) {
  13375. return toHalfFloat( val );
  13376. }
  13377. /**
  13378. * Returns a single precision floating point value (FP32) from the given half
  13379. * precision floating point value (FP16).
  13380. *
  13381. * @param {number} val - A half precision floating point value.
  13382. * @return {number} The FP32 value.
  13383. */
  13384. static fromHalfFloat( val ) {
  13385. return fromHalfFloat( val );
  13386. }
  13387. }
  13388. const _vector$9 = /*@__PURE__*/ new Vector3();
  13389. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13390. let _id$2 = 0;
  13391. /**
  13392. * This class stores data for an attribute (such as vertex positions, face
  13393. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13394. * a geometry, which allows for more efficient passing of data to the GPU.
  13395. *
  13396. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13397. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13398. */
  13399. class BufferAttribute {
  13400. /**
  13401. * Constructs a new buffer attribute.
  13402. *
  13403. * @param {TypedArray} array - The array holding the attribute data.
  13404. * @param {number} itemSize - The item size.
  13405. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13406. */
  13407. constructor( array, itemSize, normalized = false ) {
  13408. if ( Array.isArray( array ) ) {
  13409. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13410. }
  13411. /**
  13412. * This flag can be used for type testing.
  13413. *
  13414. * @type {boolean}
  13415. * @readonly
  13416. * @default true
  13417. */
  13418. this.isBufferAttribute = true;
  13419. /**
  13420. * The ID of the buffer attribute.
  13421. *
  13422. * @name BufferAttribute#id
  13423. * @type {number}
  13424. * @readonly
  13425. */
  13426. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  13427. /**
  13428. * The name of the buffer attribute.
  13429. *
  13430. * @type {string}
  13431. */
  13432. this.name = '';
  13433. /**
  13434. * The array holding the attribute data. It should have `itemSize * numVertices`
  13435. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13436. *
  13437. * @type {TypedArray}
  13438. */
  13439. this.array = array;
  13440. /**
  13441. * The number of values of the array that should be associated with a particular vertex.
  13442. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13443. * normal, or color), then the value should be `3`.
  13444. *
  13445. * @type {number}
  13446. */
  13447. this.itemSize = itemSize;
  13448. /**
  13449. * Represents the number of items this buffer attribute stores. It is internally computed
  13450. * by dividing the `array` length by the `itemSize`.
  13451. *
  13452. * @type {number}
  13453. * @readonly
  13454. */
  13455. this.count = array !== undefined ? array.length / itemSize : 0;
  13456. /**
  13457. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13458. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13459. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13460. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13461. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13462. *
  13463. * @type {boolean}
  13464. */
  13465. this.normalized = normalized;
  13466. /**
  13467. * Defines the intended usage pattern of the data store for optimization purposes.
  13468. *
  13469. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13470. * instantiate a new one and set the desired usage before the next render.
  13471. *
  13472. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13473. * @default StaticDrawUsage
  13474. */
  13475. this.usage = StaticDrawUsage;
  13476. /**
  13477. * This can be used to only update some components of stored vectors (for example, just the
  13478. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13479. *
  13480. * @type {Array<Object>}
  13481. */
  13482. this.updateRanges = [];
  13483. /**
  13484. * Configures the bound GPU type for use in shaders.
  13485. *
  13486. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13487. * For lower precision float types, use `Float16BufferAttribute`.
  13488. *
  13489. * @type {(FloatType|IntType)}
  13490. * @default FloatType
  13491. */
  13492. this.gpuType = FloatType;
  13493. /**
  13494. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13495. *
  13496. * @type {number}
  13497. */
  13498. this.version = 0;
  13499. }
  13500. /**
  13501. * A callback function that is executed after the renderer has transferred the attribute
  13502. * array data to the GPU.
  13503. */
  13504. onUploadCallback() {}
  13505. /**
  13506. * Flag to indicate that this attribute has changed and should be re-sent to
  13507. * the GPU. Set this to `true` when you modify the value of the array.
  13508. *
  13509. * @type {number}
  13510. * @default false
  13511. * @param {boolean} value
  13512. */
  13513. set needsUpdate( value ) {
  13514. if ( value === true ) this.version ++;
  13515. }
  13516. /**
  13517. * Sets the usage of this buffer attribute.
  13518. *
  13519. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13520. * @return {BufferAttribute} A reference to this buffer attribute.
  13521. */
  13522. setUsage( value ) {
  13523. this.usage = value;
  13524. return this;
  13525. }
  13526. /**
  13527. * Adds a range of data in the data array to be updated on the GPU.
  13528. *
  13529. * @param {number} start - Position at which to start update.
  13530. * @param {number} count - The number of components to update.
  13531. */
  13532. addUpdateRange( start, count ) {
  13533. this.updateRanges.push( { start, count } );
  13534. }
  13535. /**
  13536. * Clears the update ranges.
  13537. */
  13538. clearUpdateRanges() {
  13539. this.updateRanges.length = 0;
  13540. }
  13541. /**
  13542. * Copies the values of the given buffer attribute to this instance.
  13543. *
  13544. * @param {BufferAttribute} source - The buffer attribute to copy.
  13545. * @return {BufferAttribute} A reference to this instance.
  13546. */
  13547. copy( source ) {
  13548. this.name = source.name;
  13549. this.array = new source.array.constructor( source.array );
  13550. this.itemSize = source.itemSize;
  13551. this.count = source.count;
  13552. this.normalized = source.normalized;
  13553. this.usage = source.usage;
  13554. this.gpuType = source.gpuType;
  13555. return this;
  13556. }
  13557. /**
  13558. * Copies a vector from the given buffer attribute to this one. The start
  13559. * and destination position in the attribute buffers are represented by the
  13560. * given indices.
  13561. *
  13562. * @param {number} index1 - The destination index into this buffer attribute.
  13563. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13564. * @param {number} index2 - The source index into the given buffer attribute.
  13565. * @return {BufferAttribute} A reference to this instance.
  13566. */
  13567. copyAt( index1, attribute, index2 ) {
  13568. index1 *= this.itemSize;
  13569. index2 *= attribute.itemSize;
  13570. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13571. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13572. }
  13573. return this;
  13574. }
  13575. /**
  13576. * Copies the given array data into this buffer attribute.
  13577. *
  13578. * @param {(TypedArray|Array)} array - The array to copy.
  13579. * @return {BufferAttribute} A reference to this instance.
  13580. */
  13581. copyArray( array ) {
  13582. this.array.set( array );
  13583. return this;
  13584. }
  13585. /**
  13586. * Applies the given 3x3 matrix to the given attribute. Works with
  13587. * item size `2` and `3`.
  13588. *
  13589. * @param {Matrix3} m - The matrix to apply.
  13590. * @return {BufferAttribute} A reference to this instance.
  13591. */
  13592. applyMatrix3( m ) {
  13593. if ( this.itemSize === 2 ) {
  13594. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13595. _vector2$1.fromBufferAttribute( this, i );
  13596. _vector2$1.applyMatrix3( m );
  13597. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13598. }
  13599. } else if ( this.itemSize === 3 ) {
  13600. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13601. _vector$9.fromBufferAttribute( this, i );
  13602. _vector$9.applyMatrix3( m );
  13603. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13604. }
  13605. }
  13606. return this;
  13607. }
  13608. /**
  13609. * Applies the given 4x4 matrix to the given attribute. Only works with
  13610. * item size `3`.
  13611. *
  13612. * @param {Matrix4} m - The matrix to apply.
  13613. * @return {BufferAttribute} A reference to this instance.
  13614. */
  13615. applyMatrix4( m ) {
  13616. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13617. _vector$9.fromBufferAttribute( this, i );
  13618. _vector$9.applyMatrix4( m );
  13619. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13620. }
  13621. return this;
  13622. }
  13623. /**
  13624. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13625. * item size `3`.
  13626. *
  13627. * @param {Matrix3} m - The normal matrix to apply.
  13628. * @return {BufferAttribute} A reference to this instance.
  13629. */
  13630. applyNormalMatrix( m ) {
  13631. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13632. _vector$9.fromBufferAttribute( this, i );
  13633. _vector$9.applyNormalMatrix( m );
  13634. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13635. }
  13636. return this;
  13637. }
  13638. /**
  13639. * Applies the given 4x4 matrix to the given attribute. Only works with
  13640. * item size `3` and with direction vectors.
  13641. *
  13642. * @param {Matrix4} m - The matrix to apply.
  13643. * @return {BufferAttribute} A reference to this instance.
  13644. */
  13645. transformDirection( m ) {
  13646. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13647. _vector$9.fromBufferAttribute( this, i );
  13648. _vector$9.transformDirection( m );
  13649. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13650. }
  13651. return this;
  13652. }
  13653. /**
  13654. * Sets the given array data in the buffer attribute.
  13655. *
  13656. * @param {(TypedArray|Array)} value - The array data to set.
  13657. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13658. * @return {BufferAttribute} A reference to this instance.
  13659. */
  13660. set( value, offset = 0 ) {
  13661. // Matching BufferAttribute constructor, do not normalize the array.
  13662. this.array.set( value, offset );
  13663. return this;
  13664. }
  13665. /**
  13666. * Returns the given component of the vector at the given index.
  13667. *
  13668. * @param {number} index - The index into the buffer attribute.
  13669. * @param {number} component - The component index.
  13670. * @return {number} The returned value.
  13671. */
  13672. getComponent( index, component ) {
  13673. let value = this.array[ index * this.itemSize + component ];
  13674. if ( this.normalized ) value = denormalize( value, this.array );
  13675. return value;
  13676. }
  13677. /**
  13678. * Sets the given value to the given component of the vector at the given index.
  13679. *
  13680. * @param {number} index - The index into the buffer attribute.
  13681. * @param {number} component - The component index.
  13682. * @param {number} value - The value to set.
  13683. * @return {BufferAttribute} A reference to this instance.
  13684. */
  13685. setComponent( index, component, value ) {
  13686. if ( this.normalized ) value = normalize( value, this.array );
  13687. this.array[ index * this.itemSize + component ] = value;
  13688. return this;
  13689. }
  13690. /**
  13691. * Returns the x component of the vector at the given index.
  13692. *
  13693. * @param {number} index - The index into the buffer attribute.
  13694. * @return {number} The x component.
  13695. */
  13696. getX( index ) {
  13697. let x = this.array[ index * this.itemSize ];
  13698. if ( this.normalized ) x = denormalize( x, this.array );
  13699. return x;
  13700. }
  13701. /**
  13702. * Sets the x component of the vector at the given index.
  13703. *
  13704. * @param {number} index - The index into the buffer attribute.
  13705. * @param {number} x - The value to set.
  13706. * @return {BufferAttribute} A reference to this instance.
  13707. */
  13708. setX( index, x ) {
  13709. if ( this.normalized ) x = normalize( x, this.array );
  13710. this.array[ index * this.itemSize ] = x;
  13711. return this;
  13712. }
  13713. /**
  13714. * Returns the y component of the vector at the given index.
  13715. *
  13716. * @param {number} index - The index into the buffer attribute.
  13717. * @return {number} The y component.
  13718. */
  13719. getY( index ) {
  13720. let y = this.array[ index * this.itemSize + 1 ];
  13721. if ( this.normalized ) y = denormalize( y, this.array );
  13722. return y;
  13723. }
  13724. /**
  13725. * Sets the y component of the vector at the given index.
  13726. *
  13727. * @param {number} index - The index into the buffer attribute.
  13728. * @param {number} y - The value to set.
  13729. * @return {BufferAttribute} A reference to this instance.
  13730. */
  13731. setY( index, y ) {
  13732. if ( this.normalized ) y = normalize( y, this.array );
  13733. this.array[ index * this.itemSize + 1 ] = y;
  13734. return this;
  13735. }
  13736. /**
  13737. * Returns the z component of the vector at the given index.
  13738. *
  13739. * @param {number} index - The index into the buffer attribute.
  13740. * @return {number} The z component.
  13741. */
  13742. getZ( index ) {
  13743. let z = this.array[ index * this.itemSize + 2 ];
  13744. if ( this.normalized ) z = denormalize( z, this.array );
  13745. return z;
  13746. }
  13747. /**
  13748. * Sets the z component of the vector at the given index.
  13749. *
  13750. * @param {number} index - The index into the buffer attribute.
  13751. * @param {number} z - The value to set.
  13752. * @return {BufferAttribute} A reference to this instance.
  13753. */
  13754. setZ( index, z ) {
  13755. if ( this.normalized ) z = normalize( z, this.array );
  13756. this.array[ index * this.itemSize + 2 ] = z;
  13757. return this;
  13758. }
  13759. /**
  13760. * Returns the w component of the vector at the given index.
  13761. *
  13762. * @param {number} index - The index into the buffer attribute.
  13763. * @return {number} The w component.
  13764. */
  13765. getW( index ) {
  13766. let w = this.array[ index * this.itemSize + 3 ];
  13767. if ( this.normalized ) w = denormalize( w, this.array );
  13768. return w;
  13769. }
  13770. /**
  13771. * Sets the w component of the vector at the given index.
  13772. *
  13773. * @param {number} index - The index into the buffer attribute.
  13774. * @param {number} w - The value to set.
  13775. * @return {BufferAttribute} A reference to this instance.
  13776. */
  13777. setW( index, w ) {
  13778. if ( this.normalized ) w = normalize( w, this.array );
  13779. this.array[ index * this.itemSize + 3 ] = w;
  13780. return this;
  13781. }
  13782. /**
  13783. * Sets the x and y component of the vector at the given index.
  13784. *
  13785. * @param {number} index - The index into the buffer attribute.
  13786. * @param {number} x - The value for the x component to set.
  13787. * @param {number} y - The value for the y component to set.
  13788. * @return {BufferAttribute} A reference to this instance.
  13789. */
  13790. setXY( index, x, y ) {
  13791. index *= this.itemSize;
  13792. if ( this.normalized ) {
  13793. x = normalize( x, this.array );
  13794. y = normalize( y, this.array );
  13795. }
  13796. this.array[ index + 0 ] = x;
  13797. this.array[ index + 1 ] = y;
  13798. return this;
  13799. }
  13800. /**
  13801. * Sets the x, y and z component of the vector at the given index.
  13802. *
  13803. * @param {number} index - The index into the buffer attribute.
  13804. * @param {number} x - The value for the x component to set.
  13805. * @param {number} y - The value for the y component to set.
  13806. * @param {number} z - The value for the z component to set.
  13807. * @return {BufferAttribute} A reference to this instance.
  13808. */
  13809. setXYZ( index, x, y, z ) {
  13810. index *= this.itemSize;
  13811. if ( this.normalized ) {
  13812. x = normalize( x, this.array );
  13813. y = normalize( y, this.array );
  13814. z = normalize( z, this.array );
  13815. }
  13816. this.array[ index + 0 ] = x;
  13817. this.array[ index + 1 ] = y;
  13818. this.array[ index + 2 ] = z;
  13819. return this;
  13820. }
  13821. /**
  13822. * Sets the x, y, z and w component of the vector at the given index.
  13823. *
  13824. * @param {number} index - The index into the buffer attribute.
  13825. * @param {number} x - The value for the x component to set.
  13826. * @param {number} y - The value for the y component to set.
  13827. * @param {number} z - The value for the z component to set.
  13828. * @param {number} w - The value for the w component to set.
  13829. * @return {BufferAttribute} A reference to this instance.
  13830. */
  13831. setXYZW( index, x, y, z, w ) {
  13832. index *= this.itemSize;
  13833. if ( this.normalized ) {
  13834. x = normalize( x, this.array );
  13835. y = normalize( y, this.array );
  13836. z = normalize( z, this.array );
  13837. w = normalize( w, this.array );
  13838. }
  13839. this.array[ index + 0 ] = x;
  13840. this.array[ index + 1 ] = y;
  13841. this.array[ index + 2 ] = z;
  13842. this.array[ index + 3 ] = w;
  13843. return this;
  13844. }
  13845. /**
  13846. * Sets the given callback function that is executed after the Renderer has transferred
  13847. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13848. * the upload when attribute data are not needed anymore on the CPU side.
  13849. *
  13850. * @param {Function} callback - The `onUpload()` callback.
  13851. * @return {BufferAttribute} A reference to this instance.
  13852. */
  13853. onUpload( callback ) {
  13854. this.onUploadCallback = callback;
  13855. return this;
  13856. }
  13857. /**
  13858. * Returns a new buffer attribute with copied values from this instance.
  13859. *
  13860. * @return {BufferAttribute} A clone of this instance.
  13861. */
  13862. clone() {
  13863. return new this.constructor( this.array, this.itemSize ).copy( this );
  13864. }
  13865. /**
  13866. * Serializes the buffer attribute into JSON.
  13867. *
  13868. * @return {Object} A JSON object representing the serialized buffer attribute.
  13869. */
  13870. toJSON() {
  13871. const data = {
  13872. itemSize: this.itemSize,
  13873. type: this.array.constructor.name,
  13874. array: Array.from( this.array ),
  13875. normalized: this.normalized
  13876. };
  13877. if ( this.name !== '' ) data.name = this.name;
  13878. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13879. return data;
  13880. }
  13881. }
  13882. /**
  13883. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13884. * a plain `Array` instance.
  13885. *
  13886. * @augments BufferAttribute
  13887. */
  13888. class Int8BufferAttribute extends BufferAttribute {
  13889. /**
  13890. * Constructs a new buffer attribute.
  13891. *
  13892. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13893. * @param {number} itemSize - The item size.
  13894. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13895. */
  13896. constructor( array, itemSize, normalized ) {
  13897. super( new Int8Array( array ), itemSize, normalized );
  13898. }
  13899. }
  13900. /**
  13901. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13902. * a plain `Array` instance.
  13903. *
  13904. * @augments BufferAttribute
  13905. */
  13906. class Uint8BufferAttribute extends BufferAttribute {
  13907. /**
  13908. * Constructs a new buffer attribute.
  13909. *
  13910. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13911. * @param {number} itemSize - The item size.
  13912. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13913. */
  13914. constructor( array, itemSize, normalized ) {
  13915. super( new Uint8Array( array ), itemSize, normalized );
  13916. }
  13917. }
  13918. /**
  13919. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13920. * a plain `Array` instance.
  13921. *
  13922. * @augments BufferAttribute
  13923. */
  13924. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13925. /**
  13926. * Constructs a new buffer attribute.
  13927. *
  13928. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13929. * @param {number} itemSize - The item size.
  13930. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13931. */
  13932. constructor( array, itemSize, normalized ) {
  13933. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13934. }
  13935. }
  13936. /**
  13937. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13938. * a plain `Array` instance.
  13939. *
  13940. * @augments BufferAttribute
  13941. */
  13942. class Int16BufferAttribute extends BufferAttribute {
  13943. /**
  13944. * Constructs a new buffer attribute.
  13945. *
  13946. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13947. * @param {number} itemSize - The item size.
  13948. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13949. */
  13950. constructor( array, itemSize, normalized ) {
  13951. super( new Int16Array( array ), itemSize, normalized );
  13952. }
  13953. }
  13954. /**
  13955. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13956. * a plain `Array` instance.
  13957. *
  13958. * @augments BufferAttribute
  13959. */
  13960. class Uint16BufferAttribute extends BufferAttribute {
  13961. /**
  13962. * Constructs a new buffer attribute.
  13963. *
  13964. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13965. * @param {number} itemSize - The item size.
  13966. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13967. */
  13968. constructor( array, itemSize, normalized ) {
  13969. super( new Uint16Array( array ), itemSize, normalized );
  13970. }
  13971. }
  13972. /**
  13973. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13974. * a plain `Array` instance.
  13975. *
  13976. * @augments BufferAttribute
  13977. */
  13978. class Int32BufferAttribute extends BufferAttribute {
  13979. /**
  13980. * Constructs a new buffer attribute.
  13981. *
  13982. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13983. * @param {number} itemSize - The item size.
  13984. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13985. */
  13986. constructor( array, itemSize, normalized ) {
  13987. super( new Int32Array( array ), itemSize, normalized );
  13988. }
  13989. }
  13990. /**
  13991. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13992. * a plain `Array` instance.
  13993. *
  13994. * @augments BufferAttribute
  13995. */
  13996. class Uint32BufferAttribute extends BufferAttribute {
  13997. /**
  13998. * Constructs a new buffer attribute.
  13999. *
  14000. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14001. * @param {number} itemSize - The item size.
  14002. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14003. */
  14004. constructor( array, itemSize, normalized ) {
  14005. super( new Uint32Array( array ), itemSize, normalized );
  14006. }
  14007. }
  14008. /**
  14009. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14010. * a plain `Array` instance.
  14011. *
  14012. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14013. * browser support is still problematic.
  14014. *
  14015. * @augments BufferAttribute
  14016. */
  14017. class Float16BufferAttribute extends BufferAttribute {
  14018. /**
  14019. * Constructs a new buffer attribute.
  14020. *
  14021. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14022. * @param {number} itemSize - The item size.
  14023. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14024. */
  14025. constructor( array, itemSize, normalized ) {
  14026. super( new Uint16Array( array ), itemSize, normalized );
  14027. this.isFloat16BufferAttribute = true;
  14028. }
  14029. getX( index ) {
  14030. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14031. if ( this.normalized ) x = denormalize( x, this.array );
  14032. return x;
  14033. }
  14034. setX( index, x ) {
  14035. if ( this.normalized ) x = normalize( x, this.array );
  14036. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14037. return this;
  14038. }
  14039. getY( index ) {
  14040. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14041. if ( this.normalized ) y = denormalize( y, this.array );
  14042. return y;
  14043. }
  14044. setY( index, y ) {
  14045. if ( this.normalized ) y = normalize( y, this.array );
  14046. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14047. return this;
  14048. }
  14049. getZ( index ) {
  14050. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14051. if ( this.normalized ) z = denormalize( z, this.array );
  14052. return z;
  14053. }
  14054. setZ( index, z ) {
  14055. if ( this.normalized ) z = normalize( z, this.array );
  14056. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14057. return this;
  14058. }
  14059. getW( index ) {
  14060. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14061. if ( this.normalized ) w = denormalize( w, this.array );
  14062. return w;
  14063. }
  14064. setW( index, w ) {
  14065. if ( this.normalized ) w = normalize( w, this.array );
  14066. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14067. return this;
  14068. }
  14069. setXY( index, x, y ) {
  14070. index *= this.itemSize;
  14071. if ( this.normalized ) {
  14072. x = normalize( x, this.array );
  14073. y = normalize( y, this.array );
  14074. }
  14075. this.array[ index + 0 ] = toHalfFloat( x );
  14076. this.array[ index + 1 ] = toHalfFloat( y );
  14077. return this;
  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 ] = toHalfFloat( x );
  14087. this.array[ index + 1 ] = toHalfFloat( y );
  14088. this.array[ index + 2 ] = toHalfFloat( z );
  14089. return this;
  14090. }
  14091. setXYZW( index, x, y, z, w ) {
  14092. index *= this.itemSize;
  14093. if ( this.normalized ) {
  14094. x = normalize( x, this.array );
  14095. y = normalize( y, this.array );
  14096. z = normalize( z, this.array );
  14097. w = normalize( w, this.array );
  14098. }
  14099. this.array[ index + 0 ] = toHalfFloat( x );
  14100. this.array[ index + 1 ] = toHalfFloat( y );
  14101. this.array[ index + 2 ] = toHalfFloat( z );
  14102. this.array[ index + 3 ] = toHalfFloat( w );
  14103. return this;
  14104. }
  14105. }
  14106. /**
  14107. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14108. * a plain `Array` instance.
  14109. *
  14110. * @augments BufferAttribute
  14111. */
  14112. class Float32BufferAttribute extends BufferAttribute {
  14113. /**
  14114. * Constructs a new buffer attribute.
  14115. *
  14116. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14117. * @param {number} itemSize - The item size.
  14118. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14119. */
  14120. constructor( array, itemSize, normalized ) {
  14121. super( new Float32Array( array ), itemSize, normalized );
  14122. }
  14123. }
  14124. let _id$1 = 0;
  14125. const _m1 = /*@__PURE__*/ new Matrix4();
  14126. const _obj = /*@__PURE__*/ new Object3D();
  14127. const _offset = /*@__PURE__*/ new Vector3();
  14128. const _box$2 = /*@__PURE__*/ new Box3();
  14129. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14130. const _vector$8 = /*@__PURE__*/ new Vector3();
  14131. /**
  14132. * A representation of mesh, line, or point geometry. Includes vertex
  14133. * positions, face indices, normals, colors, UVs, and custom attributes
  14134. * within buffers, reducing the cost of passing all this data to the GPU.
  14135. *
  14136. * ```js
  14137. * const geometry = new THREE.BufferGeometry();
  14138. * // create a simple square shape. We duplicate the top left and bottom right
  14139. * // vertices because each vertex needs to appear once per triangle.
  14140. * const vertices = new Float32Array( [
  14141. * -1.0, -1.0, 1.0, // v0
  14142. * 1.0, -1.0, 1.0, // v1
  14143. * 1.0, 1.0, 1.0, // v2
  14144. *
  14145. * 1.0, 1.0, 1.0, // v3
  14146. * -1.0, 1.0, 1.0, // v4
  14147. * -1.0, -1.0, 1.0 // v5
  14148. * ] );
  14149. * // itemSize = 3 because there are 3 values (components) per vertex
  14150. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14151. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14152. * const mesh = new THREE.Mesh( geometry, material );
  14153. * ```
  14154. *
  14155. * @augments EventDispatcher
  14156. */
  14157. class BufferGeometry extends EventDispatcher {
  14158. /**
  14159. * Constructs a new geometry.
  14160. */
  14161. constructor() {
  14162. super();
  14163. /**
  14164. * This flag can be used for type testing.
  14165. *
  14166. * @type {boolean}
  14167. * @readonly
  14168. * @default true
  14169. */
  14170. this.isBufferGeometry = true;
  14171. /**
  14172. * The ID of the geometry.
  14173. *
  14174. * @name BufferGeometry#id
  14175. * @type {number}
  14176. * @readonly
  14177. */
  14178. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  14179. /**
  14180. * The UUID of the geometry.
  14181. *
  14182. * @type {string}
  14183. * @readonly
  14184. */
  14185. this.uuid = generateUUID();
  14186. /**
  14187. * The name of the geometry.
  14188. *
  14189. * @type {string}
  14190. */
  14191. this.name = '';
  14192. this.type = 'BufferGeometry';
  14193. /**
  14194. * Allows for vertices to be re-used across multiple triangles; this is
  14195. * called using "indexed triangles". Each triangle is associated with the
  14196. * indices of three vertices. This attribute therefore stores the index of
  14197. * each vertex for each triangular face. If this attribute is not set, the
  14198. * renderer assumes that each three contiguous positions represent a single triangle.
  14199. *
  14200. * @type {?BufferAttribute}
  14201. * @default null
  14202. */
  14203. this.index = null;
  14204. /**
  14205. * A (storage) buffer attribute which was generated with a compute shader and
  14206. * now defines indirect draw calls.
  14207. *
  14208. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14209. *
  14210. * @type {?BufferAttribute}
  14211. * @default null
  14212. */
  14213. this.indirect = null;
  14214. /**
  14215. * This dictionary has as id the name of the attribute to be set and as value
  14216. * the buffer attribute to set it to. Rather than accessing this property directly,
  14217. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14218. *
  14219. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14220. */
  14221. this.attributes = {};
  14222. /**
  14223. * This dictionary holds the morph targets of the geometry.
  14224. *
  14225. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14226. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14227. *
  14228. * @type {Object}
  14229. */
  14230. this.morphAttributes = {};
  14231. /**
  14232. * Used to control the morph target behavior; when set to `true`, the morph
  14233. * target data is treated as relative offsets, rather than as absolute
  14234. * positions/normals.
  14235. *
  14236. * @type {boolean}
  14237. * @default false
  14238. */
  14239. this.morphTargetsRelative = false;
  14240. /**
  14241. * Split the geometry into groups, each of which will be rendered in a
  14242. * separate draw call. This allows an array of materials to be used with the geometry.
  14243. *
  14244. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14245. *
  14246. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14247. * indices, and must not leave vertices or indices unused.
  14248. *
  14249. * @type {Array<Object>}
  14250. */
  14251. this.groups = [];
  14252. /**
  14253. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14254. *
  14255. * @type {Box3}
  14256. * @default null
  14257. */
  14258. this.boundingBox = null;
  14259. /**
  14260. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14261. *
  14262. * @type {Sphere}
  14263. * @default null
  14264. */
  14265. this.boundingSphere = null;
  14266. /**
  14267. * Determines the part of the geometry to render. This should not be set directly,
  14268. * instead use `setDrawRange()`.
  14269. *
  14270. * @type {{start:number,count:number}}
  14271. */
  14272. this.drawRange = { start: 0, count: Infinity };
  14273. /**
  14274. * An object that can be used to store custom data about the geometry.
  14275. * It should not hold references to functions as these will not be cloned.
  14276. *
  14277. * @type {Object}
  14278. */
  14279. this.userData = {};
  14280. }
  14281. /**
  14282. * Returns the index of this geometry.
  14283. *
  14284. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14285. */
  14286. getIndex() {
  14287. return this.index;
  14288. }
  14289. /**
  14290. * Sets the given index to this geometry.
  14291. *
  14292. * @param {Array<number>|BufferAttribute} index - The index to set.
  14293. * @return {BufferGeometry} A reference to this instance.
  14294. */
  14295. setIndex( index ) {
  14296. if ( Array.isArray( index ) ) {
  14297. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14298. } else {
  14299. this.index = index;
  14300. }
  14301. return this;
  14302. }
  14303. /**
  14304. * Sets the given indirect attribute to this geometry.
  14305. *
  14306. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14307. * @return {BufferGeometry} A reference to this instance.
  14308. */
  14309. setIndirect( indirect ) {
  14310. this.indirect = indirect;
  14311. return this;
  14312. }
  14313. /**
  14314. * Returns the indirect attribute of this geometry.
  14315. *
  14316. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14317. */
  14318. getIndirect() {
  14319. return this.indirect;
  14320. }
  14321. /**
  14322. * Returns the buffer attribute for the given name.
  14323. *
  14324. * @param {string} name - The attribute name.
  14325. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14326. * Returns `undefined` if not attribute has been found.
  14327. */
  14328. getAttribute( name ) {
  14329. return this.attributes[ name ];
  14330. }
  14331. /**
  14332. * Sets the given attribute for the given name.
  14333. *
  14334. * @param {string} name - The attribute name.
  14335. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14336. * @return {BufferGeometry} A reference to this instance.
  14337. */
  14338. setAttribute( name, attribute ) {
  14339. this.attributes[ name ] = attribute;
  14340. return this;
  14341. }
  14342. /**
  14343. * Deletes the attribute for the given name.
  14344. *
  14345. * @param {string} name - The attribute name to delete.
  14346. * @return {BufferGeometry} A reference to this instance.
  14347. */
  14348. deleteAttribute( name ) {
  14349. delete this.attributes[ name ];
  14350. return this;
  14351. }
  14352. /**
  14353. * Returns `true` if this geometry has an attribute for the given name.
  14354. *
  14355. * @param {string} name - The attribute name.
  14356. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14357. */
  14358. hasAttribute( name ) {
  14359. return this.attributes[ name ] !== undefined;
  14360. }
  14361. /**
  14362. * Adds a group to this geometry.
  14363. *
  14364. * @param {number} start - The first element in this draw call. That is the first
  14365. * vertex for non-indexed geometry, otherwise the first triangle index.
  14366. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14367. * @param {number} [materialIndex=0] - The material array index to use.
  14368. */
  14369. addGroup( start, count, materialIndex = 0 ) {
  14370. this.groups.push( {
  14371. start: start,
  14372. count: count,
  14373. materialIndex: materialIndex
  14374. } );
  14375. }
  14376. /**
  14377. * Clears all groups.
  14378. */
  14379. clearGroups() {
  14380. this.groups = [];
  14381. }
  14382. /**
  14383. * Sets the draw range for this geometry.
  14384. *
  14385. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14386. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14387. * For indexed BufferGeometry, `count` is the number of indices to render.
  14388. */
  14389. setDrawRange( start, count ) {
  14390. this.drawRange.start = start;
  14391. this.drawRange.count = count;
  14392. }
  14393. /**
  14394. * Applies the given 4x4 transformation matrix to the geometry.
  14395. *
  14396. * @param {Matrix4} matrix - The matrix to apply.
  14397. * @return {BufferGeometry} A reference to this instance.
  14398. */
  14399. applyMatrix4( matrix ) {
  14400. const position = this.attributes.position;
  14401. if ( position !== undefined ) {
  14402. position.applyMatrix4( matrix );
  14403. position.needsUpdate = true;
  14404. }
  14405. const normal = this.attributes.normal;
  14406. if ( normal !== undefined ) {
  14407. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14408. normal.applyNormalMatrix( normalMatrix );
  14409. normal.needsUpdate = true;
  14410. }
  14411. const tangent = this.attributes.tangent;
  14412. if ( tangent !== undefined ) {
  14413. tangent.transformDirection( matrix );
  14414. tangent.needsUpdate = true;
  14415. }
  14416. if ( this.boundingBox !== null ) {
  14417. this.computeBoundingBox();
  14418. }
  14419. if ( this.boundingSphere !== null ) {
  14420. this.computeBoundingSphere();
  14421. }
  14422. return this;
  14423. }
  14424. /**
  14425. * Applies the rotation represented by the Quaternion to the geometry.
  14426. *
  14427. * @param {Quaternion} q - The Quaternion to apply.
  14428. * @return {BufferGeometry} A reference to this instance.
  14429. */
  14430. applyQuaternion( q ) {
  14431. _m1.makeRotationFromQuaternion( q );
  14432. this.applyMatrix4( _m1 );
  14433. return this;
  14434. }
  14435. /**
  14436. * Rotates the geometry about the X axis. This is typically done as a one time
  14437. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14438. * real-time mesh rotation.
  14439. *
  14440. * @param {number} angle - The angle in radians.
  14441. * @return {BufferGeometry} A reference to this instance.
  14442. */
  14443. rotateX( angle ) {
  14444. // rotate geometry around world x-axis
  14445. _m1.makeRotationX( angle );
  14446. this.applyMatrix4( _m1 );
  14447. return this;
  14448. }
  14449. /**
  14450. * Rotates the geometry about the Y axis. This is typically done as a one time
  14451. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14452. * real-time mesh rotation.
  14453. *
  14454. * @param {number} angle - The angle in radians.
  14455. * @return {BufferGeometry} A reference to this instance.
  14456. */
  14457. rotateY( angle ) {
  14458. // rotate geometry around world y-axis
  14459. _m1.makeRotationY( angle );
  14460. this.applyMatrix4( _m1 );
  14461. return this;
  14462. }
  14463. /**
  14464. * Rotates the geometry about the Z axis. This is typically done as a one time
  14465. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14466. * real-time mesh rotation.
  14467. *
  14468. * @param {number} angle - The angle in radians.
  14469. * @return {BufferGeometry} A reference to this instance.
  14470. */
  14471. rotateZ( angle ) {
  14472. // rotate geometry around world z-axis
  14473. _m1.makeRotationZ( angle );
  14474. this.applyMatrix4( _m1 );
  14475. return this;
  14476. }
  14477. /**
  14478. * Translates the geometry. This is typically done as a one time
  14479. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14480. * real-time mesh rotation.
  14481. *
  14482. * @param {number} x - The x offset.
  14483. * @param {number} y - The y offset.
  14484. * @param {number} z - The z offset.
  14485. * @return {BufferGeometry} A reference to this instance.
  14486. */
  14487. translate( x, y, z ) {
  14488. // translate geometry
  14489. _m1.makeTranslation( x, y, z );
  14490. this.applyMatrix4( _m1 );
  14491. return this;
  14492. }
  14493. /**
  14494. * Scales the geometry. This is typically done as a one time
  14495. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14496. * real-time mesh rotation.
  14497. *
  14498. * @param {number} x - The x scale.
  14499. * @param {number} y - The y scale.
  14500. * @param {number} z - The z scale.
  14501. * @return {BufferGeometry} A reference to this instance.
  14502. */
  14503. scale( x, y, z ) {
  14504. // scale geometry
  14505. _m1.makeScale( x, y, z );
  14506. this.applyMatrix4( _m1 );
  14507. return this;
  14508. }
  14509. /**
  14510. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14511. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14512. * real-time mesh rotation.
  14513. *
  14514. * @param {Vector3} vector - The target point.
  14515. * @return {BufferGeometry} A reference to this instance.
  14516. */
  14517. lookAt( vector ) {
  14518. _obj.lookAt( vector );
  14519. _obj.updateMatrix();
  14520. this.applyMatrix4( _obj.matrix );
  14521. return this;
  14522. }
  14523. /**
  14524. * Center the geometry based on its bounding box.
  14525. *
  14526. * @return {BufferGeometry} A reference to this instance.
  14527. */
  14528. center() {
  14529. this.computeBoundingBox();
  14530. this.boundingBox.getCenter( _offset ).negate();
  14531. this.translate( _offset.x, _offset.y, _offset.z );
  14532. return this;
  14533. }
  14534. /**
  14535. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14536. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14537. * set to `0`.
  14538. *
  14539. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14540. * data from the array. The length of the array must match the vertex count.
  14541. *
  14542. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14543. * @return {BufferGeometry} A reference to this instance.
  14544. */
  14545. setFromPoints( points ) {
  14546. const positionAttribute = this.getAttribute( 'position' );
  14547. if ( positionAttribute === undefined ) {
  14548. const position = [];
  14549. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14550. const point = points[ i ];
  14551. position.push( point.x, point.y, point.z || 0 );
  14552. }
  14553. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14554. } else {
  14555. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14556. for ( let i = 0; i < l; i ++ ) {
  14557. const point = points[ i ];
  14558. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14559. }
  14560. if ( points.length > positionAttribute.count ) {
  14561. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14562. }
  14563. positionAttribute.needsUpdate = true;
  14564. }
  14565. return this;
  14566. }
  14567. /**
  14568. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14569. * The bounding box is not computed by the engine; it must be computed by your app.
  14570. * You may need to recompute the bounding box if the geometry vertices are modified.
  14571. */
  14572. computeBoundingBox() {
  14573. if ( this.boundingBox === null ) {
  14574. this.boundingBox = new Box3();
  14575. }
  14576. const position = this.attributes.position;
  14577. const morphAttributesPosition = this.morphAttributes.position;
  14578. if ( position && position.isGLBufferAttribute ) {
  14579. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14580. this.boundingBox.set(
  14581. new Vector3( - Infinity, - Infinity, - Infinity ),
  14582. new Vector3( + Infinity, + Infinity, + Infinity )
  14583. );
  14584. return;
  14585. }
  14586. if ( position !== undefined ) {
  14587. this.boundingBox.setFromBufferAttribute( position );
  14588. // process morph attributes if present
  14589. if ( morphAttributesPosition ) {
  14590. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14591. const morphAttribute = morphAttributesPosition[ i ];
  14592. _box$2.setFromBufferAttribute( morphAttribute );
  14593. if ( this.morphTargetsRelative ) {
  14594. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14595. this.boundingBox.expandByPoint( _vector$8 );
  14596. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14597. this.boundingBox.expandByPoint( _vector$8 );
  14598. } else {
  14599. this.boundingBox.expandByPoint( _box$2.min );
  14600. this.boundingBox.expandByPoint( _box$2.max );
  14601. }
  14602. }
  14603. }
  14604. } else {
  14605. this.boundingBox.makeEmpty();
  14606. }
  14607. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14608. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14609. }
  14610. }
  14611. /**
  14612. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14613. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14614. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14615. */
  14616. computeBoundingSphere() {
  14617. if ( this.boundingSphere === null ) {
  14618. this.boundingSphere = new Sphere();
  14619. }
  14620. const position = this.attributes.position;
  14621. const morphAttributesPosition = this.morphAttributes.position;
  14622. if ( position && position.isGLBufferAttribute ) {
  14623. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14624. this.boundingSphere.set( new Vector3(), Infinity );
  14625. return;
  14626. }
  14627. if ( position ) {
  14628. // first, find the center of the bounding sphere
  14629. const center = this.boundingSphere.center;
  14630. _box$2.setFromBufferAttribute( position );
  14631. // process morph attributes if present
  14632. if ( morphAttributesPosition ) {
  14633. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14634. const morphAttribute = morphAttributesPosition[ i ];
  14635. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14636. if ( this.morphTargetsRelative ) {
  14637. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14638. _box$2.expandByPoint( _vector$8 );
  14639. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14640. _box$2.expandByPoint( _vector$8 );
  14641. } else {
  14642. _box$2.expandByPoint( _boxMorphTargets.min );
  14643. _box$2.expandByPoint( _boxMorphTargets.max );
  14644. }
  14645. }
  14646. }
  14647. _box$2.getCenter( center );
  14648. // second, try to find a boundingSphere with a radius smaller than the
  14649. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14650. let maxRadiusSq = 0;
  14651. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14652. _vector$8.fromBufferAttribute( position, i );
  14653. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14654. }
  14655. // process morph attributes if present
  14656. if ( morphAttributesPosition ) {
  14657. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14658. const morphAttribute = morphAttributesPosition[ i ];
  14659. const morphTargetsRelative = this.morphTargetsRelative;
  14660. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14661. _vector$8.fromBufferAttribute( morphAttribute, j );
  14662. if ( morphTargetsRelative ) {
  14663. _offset.fromBufferAttribute( position, j );
  14664. _vector$8.add( _offset );
  14665. }
  14666. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14667. }
  14668. }
  14669. }
  14670. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14671. if ( isNaN( this.boundingSphere.radius ) ) {
  14672. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14673. }
  14674. }
  14675. }
  14676. /**
  14677. * Calculates and adds a tangent attribute to this geometry.
  14678. *
  14679. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14680. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14681. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14682. */
  14683. computeTangents() {
  14684. const index = this.index;
  14685. const attributes = this.attributes;
  14686. // based on http://www.terathon.com/code/tangent.html
  14687. // (per vertex tangents)
  14688. if ( index === null ||
  14689. attributes.position === undefined ||
  14690. attributes.normal === undefined ||
  14691. attributes.uv === undefined ) {
  14692. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14693. return;
  14694. }
  14695. const positionAttribute = attributes.position;
  14696. const normalAttribute = attributes.normal;
  14697. const uvAttribute = attributes.uv;
  14698. if ( this.hasAttribute( 'tangent' ) === false ) {
  14699. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14700. }
  14701. const tangentAttribute = this.getAttribute( 'tangent' );
  14702. const tan1 = [], tan2 = [];
  14703. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14704. tan1[ i ] = new Vector3();
  14705. tan2[ i ] = new Vector3();
  14706. }
  14707. const vA = new Vector3(),
  14708. vB = new Vector3(),
  14709. vC = new Vector3(),
  14710. uvA = new Vector2(),
  14711. uvB = new Vector2(),
  14712. uvC = new Vector2(),
  14713. sdir = new Vector3(),
  14714. tdir = new Vector3();
  14715. function handleTriangle( a, b, c ) {
  14716. vA.fromBufferAttribute( positionAttribute, a );
  14717. vB.fromBufferAttribute( positionAttribute, b );
  14718. vC.fromBufferAttribute( positionAttribute, c );
  14719. uvA.fromBufferAttribute( uvAttribute, a );
  14720. uvB.fromBufferAttribute( uvAttribute, b );
  14721. uvC.fromBufferAttribute( uvAttribute, c );
  14722. vB.sub( vA );
  14723. vC.sub( vA );
  14724. uvB.sub( uvA );
  14725. uvC.sub( uvA );
  14726. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14727. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14728. if ( ! isFinite( r ) ) return;
  14729. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14730. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14731. tan1[ a ].add( sdir );
  14732. tan1[ b ].add( sdir );
  14733. tan1[ c ].add( sdir );
  14734. tan2[ a ].add( tdir );
  14735. tan2[ b ].add( tdir );
  14736. tan2[ c ].add( tdir );
  14737. }
  14738. let groups = this.groups;
  14739. if ( groups.length === 0 ) {
  14740. groups = [ {
  14741. start: 0,
  14742. count: index.count
  14743. } ];
  14744. }
  14745. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14746. const group = groups[ i ];
  14747. const start = group.start;
  14748. const count = group.count;
  14749. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14750. handleTriangle(
  14751. index.getX( j + 0 ),
  14752. index.getX( j + 1 ),
  14753. index.getX( j + 2 )
  14754. );
  14755. }
  14756. }
  14757. const tmp = new Vector3(), tmp2 = new Vector3();
  14758. const n = new Vector3(), n2 = new Vector3();
  14759. function handleVertex( v ) {
  14760. n.fromBufferAttribute( normalAttribute, v );
  14761. n2.copy( n );
  14762. const t = tan1[ v ];
  14763. // Gram-Schmidt orthogonalize
  14764. tmp.copy( t );
  14765. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14766. // Calculate handedness
  14767. tmp2.crossVectors( n2, t );
  14768. const test = tmp2.dot( tan2[ v ] );
  14769. const w = ( test < 0.0 ) ? -1 : 1.0;
  14770. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14771. }
  14772. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14773. const group = groups[ i ];
  14774. const start = group.start;
  14775. const count = group.count;
  14776. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14777. handleVertex( index.getX( j + 0 ) );
  14778. handleVertex( index.getX( j + 1 ) );
  14779. handleVertex( index.getX( j + 2 ) );
  14780. }
  14781. }
  14782. }
  14783. /**
  14784. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14785. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14786. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14787. * to be the same as the face normal.
  14788. */
  14789. computeVertexNormals() {
  14790. const index = this.index;
  14791. const positionAttribute = this.getAttribute( 'position' );
  14792. if ( positionAttribute !== undefined ) {
  14793. let normalAttribute = this.getAttribute( 'normal' );
  14794. if ( normalAttribute === undefined ) {
  14795. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14796. this.setAttribute( 'normal', normalAttribute );
  14797. } else {
  14798. // reset existing normals to zero
  14799. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14800. normalAttribute.setXYZ( i, 0, 0, 0 );
  14801. }
  14802. }
  14803. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14804. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14805. const cb = new Vector3(), ab = new Vector3();
  14806. // indexed elements
  14807. if ( index ) {
  14808. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14809. const vA = index.getX( i + 0 );
  14810. const vB = index.getX( i + 1 );
  14811. const vC = index.getX( i + 2 );
  14812. pA.fromBufferAttribute( positionAttribute, vA );
  14813. pB.fromBufferAttribute( positionAttribute, vB );
  14814. pC.fromBufferAttribute( positionAttribute, vC );
  14815. cb.subVectors( pC, pB );
  14816. ab.subVectors( pA, pB );
  14817. cb.cross( ab );
  14818. nA.fromBufferAttribute( normalAttribute, vA );
  14819. nB.fromBufferAttribute( normalAttribute, vB );
  14820. nC.fromBufferAttribute( normalAttribute, vC );
  14821. nA.add( cb );
  14822. nB.add( cb );
  14823. nC.add( cb );
  14824. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14825. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14826. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14827. }
  14828. } else {
  14829. // non-indexed elements (unconnected triangle soup)
  14830. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14831. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14832. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14833. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14834. cb.subVectors( pC, pB );
  14835. ab.subVectors( pA, pB );
  14836. cb.cross( ab );
  14837. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14838. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14839. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14840. }
  14841. }
  14842. this.normalizeNormals();
  14843. normalAttribute.needsUpdate = true;
  14844. }
  14845. }
  14846. /**
  14847. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14848. * correct lighting on the geometry surfaces.
  14849. */
  14850. normalizeNormals() {
  14851. const normals = this.attributes.normal;
  14852. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14853. _vector$8.fromBufferAttribute( normals, i );
  14854. _vector$8.normalize();
  14855. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14856. }
  14857. }
  14858. /**
  14859. * Return a new non-index version of this indexed geometry. If the geometry
  14860. * is already non-indexed, the method is a NOOP.
  14861. *
  14862. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14863. */
  14864. toNonIndexed() {
  14865. function convertBufferAttribute( attribute, indices ) {
  14866. const array = attribute.array;
  14867. const itemSize = attribute.itemSize;
  14868. const normalized = attribute.normalized;
  14869. const array2 = new array.constructor( indices.length * itemSize );
  14870. let index = 0, index2 = 0;
  14871. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14872. if ( attribute.isInterleavedBufferAttribute ) {
  14873. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14874. } else {
  14875. index = indices[ i ] * itemSize;
  14876. }
  14877. for ( let j = 0; j < itemSize; j ++ ) {
  14878. array2[ index2 ++ ] = array[ index ++ ];
  14879. }
  14880. }
  14881. return new BufferAttribute( array2, itemSize, normalized );
  14882. }
  14883. //
  14884. if ( this.index === null ) {
  14885. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14886. return this;
  14887. }
  14888. const geometry2 = new BufferGeometry();
  14889. const indices = this.index.array;
  14890. const attributes = this.attributes;
  14891. // attributes
  14892. for ( const name in attributes ) {
  14893. const attribute = attributes[ name ];
  14894. const newAttribute = convertBufferAttribute( attribute, indices );
  14895. geometry2.setAttribute( name, newAttribute );
  14896. }
  14897. // morph attributes
  14898. const morphAttributes = this.morphAttributes;
  14899. for ( const name in morphAttributes ) {
  14900. const morphArray = [];
  14901. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14902. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14903. const attribute = morphAttribute[ i ];
  14904. const newAttribute = convertBufferAttribute( attribute, indices );
  14905. morphArray.push( newAttribute );
  14906. }
  14907. geometry2.morphAttributes[ name ] = morphArray;
  14908. }
  14909. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14910. // groups
  14911. const groups = this.groups;
  14912. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14913. const group = groups[ i ];
  14914. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14915. }
  14916. return geometry2;
  14917. }
  14918. /**
  14919. * Serializes the geometry into JSON.
  14920. *
  14921. * @return {Object} A JSON object representing the serialized geometry.
  14922. */
  14923. toJSON() {
  14924. const data = {
  14925. metadata: {
  14926. version: 4.7,
  14927. type: 'BufferGeometry',
  14928. generator: 'BufferGeometry.toJSON'
  14929. }
  14930. };
  14931. // standard BufferGeometry serialization
  14932. data.uuid = this.uuid;
  14933. data.type = this.type;
  14934. if ( this.name !== '' ) data.name = this.name;
  14935. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14936. if ( this.parameters !== undefined ) {
  14937. const parameters = this.parameters;
  14938. for ( const key in parameters ) {
  14939. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14940. }
  14941. return data;
  14942. }
  14943. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14944. data.data = { attributes: {} };
  14945. const index = this.index;
  14946. if ( index !== null ) {
  14947. data.data.index = {
  14948. type: index.array.constructor.name,
  14949. array: Array.prototype.slice.call( index.array )
  14950. };
  14951. }
  14952. const attributes = this.attributes;
  14953. for ( const key in attributes ) {
  14954. const attribute = attributes[ key ];
  14955. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14956. }
  14957. const morphAttributes = {};
  14958. let hasMorphAttributes = false;
  14959. for ( const key in this.morphAttributes ) {
  14960. const attributeArray = this.morphAttributes[ key ];
  14961. const array = [];
  14962. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14963. const attribute = attributeArray[ i ];
  14964. array.push( attribute.toJSON( data.data ) );
  14965. }
  14966. if ( array.length > 0 ) {
  14967. morphAttributes[ key ] = array;
  14968. hasMorphAttributes = true;
  14969. }
  14970. }
  14971. if ( hasMorphAttributes ) {
  14972. data.data.morphAttributes = morphAttributes;
  14973. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14974. }
  14975. const groups = this.groups;
  14976. if ( groups.length > 0 ) {
  14977. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14978. }
  14979. const boundingSphere = this.boundingSphere;
  14980. if ( boundingSphere !== null ) {
  14981. data.data.boundingSphere = boundingSphere.toJSON();
  14982. }
  14983. return data;
  14984. }
  14985. /**
  14986. * Returns a new geometry with copied values from this instance.
  14987. *
  14988. * @return {BufferGeometry} A clone of this instance.
  14989. */
  14990. clone() {
  14991. return new this.constructor().copy( this );
  14992. }
  14993. /**
  14994. * Copies the values of the given geometry to this instance.
  14995. *
  14996. * @param {BufferGeometry} source - The geometry to copy.
  14997. * @return {BufferGeometry} A reference to this instance.
  14998. */
  14999. copy( source ) {
  15000. // reset
  15001. this.index = null;
  15002. this.attributes = {};
  15003. this.morphAttributes = {};
  15004. this.groups = [];
  15005. this.boundingBox = null;
  15006. this.boundingSphere = null;
  15007. // used for storing cloned, shared data
  15008. const data = {};
  15009. // name
  15010. this.name = source.name;
  15011. // index
  15012. const index = source.index;
  15013. if ( index !== null ) {
  15014. this.setIndex( index.clone() );
  15015. }
  15016. // attributes
  15017. const attributes = source.attributes;
  15018. for ( const name in attributes ) {
  15019. const attribute = attributes[ name ];
  15020. this.setAttribute( name, attribute.clone( data ) );
  15021. }
  15022. // morph attributes
  15023. const morphAttributes = source.morphAttributes;
  15024. for ( const name in morphAttributes ) {
  15025. const array = [];
  15026. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15027. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15028. array.push( morphAttribute[ i ].clone( data ) );
  15029. }
  15030. this.morphAttributes[ name ] = array;
  15031. }
  15032. this.morphTargetsRelative = source.morphTargetsRelative;
  15033. // groups
  15034. const groups = source.groups;
  15035. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15036. const group = groups[ i ];
  15037. this.addGroup( group.start, group.count, group.materialIndex );
  15038. }
  15039. // bounding box
  15040. const boundingBox = source.boundingBox;
  15041. if ( boundingBox !== null ) {
  15042. this.boundingBox = boundingBox.clone();
  15043. }
  15044. // bounding sphere
  15045. const boundingSphere = source.boundingSphere;
  15046. if ( boundingSphere !== null ) {
  15047. this.boundingSphere = boundingSphere.clone();
  15048. }
  15049. // draw range
  15050. this.drawRange.start = source.drawRange.start;
  15051. this.drawRange.count = source.drawRange.count;
  15052. // user data
  15053. this.userData = source.userData;
  15054. return this;
  15055. }
  15056. /**
  15057. * Frees the GPU-related resources allocated by this instance. Call this
  15058. * method whenever this instance is no longer used in your app.
  15059. *
  15060. * @fires BufferGeometry#dispose
  15061. */
  15062. dispose() {
  15063. this.dispatchEvent( { type: 'dispose' } );
  15064. }
  15065. }
  15066. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15067. const _ray$3 = /*@__PURE__*/ new Ray();
  15068. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15069. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15070. const _vA$1 = /*@__PURE__*/ new Vector3();
  15071. const _vB$1 = /*@__PURE__*/ new Vector3();
  15072. const _vC$1 = /*@__PURE__*/ new Vector3();
  15073. const _tempA = /*@__PURE__*/ new Vector3();
  15074. const _morphA = /*@__PURE__*/ new Vector3();
  15075. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15076. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15077. /**
  15078. * Class representing triangular polygon mesh based objects.
  15079. *
  15080. * ```js
  15081. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15082. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15083. * const mesh = new THREE.Mesh( geometry, material );
  15084. * scene.add( mesh );
  15085. * ```
  15086. *
  15087. * @augments Object3D
  15088. */
  15089. class Mesh extends Object3D {
  15090. /**
  15091. * Constructs a new mesh.
  15092. *
  15093. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15094. * @param {Material|Array<Material>} [material] - The mesh material.
  15095. */
  15096. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15097. super();
  15098. /**
  15099. * This flag can be used for type testing.
  15100. *
  15101. * @type {boolean}
  15102. * @readonly
  15103. * @default true
  15104. */
  15105. this.isMesh = true;
  15106. this.type = 'Mesh';
  15107. /**
  15108. * The mesh geometry.
  15109. *
  15110. * @type {BufferGeometry}
  15111. */
  15112. this.geometry = geometry;
  15113. /**
  15114. * The mesh material.
  15115. *
  15116. * @type {Material|Array<Material>}
  15117. * @default MeshBasicMaterial
  15118. */
  15119. this.material = material;
  15120. /**
  15121. * A dictionary representing the morph targets in the geometry. The key is the
  15122. * morph targets name, the value its attribute index. This member is `undefined`
  15123. * by default and only set when morph targets are detected in the geometry.
  15124. *
  15125. * @type {Object<String,number>|undefined}
  15126. * @default undefined
  15127. */
  15128. this.morphTargetDictionary = undefined;
  15129. /**
  15130. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15131. * is applied. This member is `undefined` by default and only set when morph targets are
  15132. * detected in the geometry.
  15133. *
  15134. * @type {Array<number>|undefined}
  15135. * @default undefined
  15136. */
  15137. this.morphTargetInfluences = undefined;
  15138. /**
  15139. * The number of instances of this mesh.
  15140. * Can only be used with {@link WebGPURenderer}.
  15141. *
  15142. * @type {number}
  15143. * @default 1
  15144. */
  15145. this.count = 1;
  15146. this.updateMorphTargets();
  15147. }
  15148. copy( source, recursive ) {
  15149. super.copy( source, recursive );
  15150. if ( source.morphTargetInfluences !== undefined ) {
  15151. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15152. }
  15153. if ( source.morphTargetDictionary !== undefined ) {
  15154. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15155. }
  15156. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15157. this.geometry = source.geometry;
  15158. return this;
  15159. }
  15160. /**
  15161. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15162. * to make sure existing morph targets can influence this 3D object.
  15163. */
  15164. updateMorphTargets() {
  15165. const geometry = this.geometry;
  15166. const morphAttributes = geometry.morphAttributes;
  15167. const keys = Object.keys( morphAttributes );
  15168. if ( keys.length > 0 ) {
  15169. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15170. if ( morphAttribute !== undefined ) {
  15171. this.morphTargetInfluences = [];
  15172. this.morphTargetDictionary = {};
  15173. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15174. const name = morphAttribute[ m ].name || String( m );
  15175. this.morphTargetInfluences.push( 0 );
  15176. this.morphTargetDictionary[ name ] = m;
  15177. }
  15178. }
  15179. }
  15180. }
  15181. /**
  15182. * Returns the local-space position of the vertex at the given index, taking into
  15183. * account the current animation state of both morph targets and skinning.
  15184. *
  15185. * @param {number} index - The vertex index.
  15186. * @param {Vector3} target - The target object that is used to store the method's result.
  15187. * @return {Vector3} The vertex position in local space.
  15188. */
  15189. getVertexPosition( index, target ) {
  15190. const geometry = this.geometry;
  15191. const position = geometry.attributes.position;
  15192. const morphPosition = geometry.morphAttributes.position;
  15193. const morphTargetsRelative = geometry.morphTargetsRelative;
  15194. target.fromBufferAttribute( position, index );
  15195. const morphInfluences = this.morphTargetInfluences;
  15196. if ( morphPosition && morphInfluences ) {
  15197. _morphA.set( 0, 0, 0 );
  15198. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15199. const influence = morphInfluences[ i ];
  15200. const morphAttribute = morphPosition[ i ];
  15201. if ( influence === 0 ) continue;
  15202. _tempA.fromBufferAttribute( morphAttribute, index );
  15203. if ( morphTargetsRelative ) {
  15204. _morphA.addScaledVector( _tempA, influence );
  15205. } else {
  15206. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15207. }
  15208. }
  15209. target.add( _morphA );
  15210. }
  15211. return target;
  15212. }
  15213. /**
  15214. * Computes intersection points between a casted ray and this line.
  15215. *
  15216. * @param {Raycaster} raycaster - The raycaster.
  15217. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15218. */
  15219. raycast( raycaster, intersects ) {
  15220. const geometry = this.geometry;
  15221. const material = this.material;
  15222. const matrixWorld = this.matrixWorld;
  15223. if ( material === undefined ) return;
  15224. // test with bounding sphere in world space
  15225. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15226. _sphere$6.copy( geometry.boundingSphere );
  15227. _sphere$6.applyMatrix4( matrixWorld );
  15228. // check distance from ray origin to bounding sphere
  15229. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15230. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15231. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15232. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15233. }
  15234. // convert ray to local space of mesh
  15235. _inverseMatrix$3.copy( matrixWorld ).invert();
  15236. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15237. // test with bounding box in local space
  15238. if ( geometry.boundingBox !== null ) {
  15239. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15240. }
  15241. // test for intersections with geometry
  15242. this._computeIntersections( raycaster, intersects, _ray$3 );
  15243. }
  15244. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15245. let intersection;
  15246. const geometry = this.geometry;
  15247. const material = this.material;
  15248. const index = geometry.index;
  15249. const position = geometry.attributes.position;
  15250. const uv = geometry.attributes.uv;
  15251. const uv1 = geometry.attributes.uv1;
  15252. const normal = geometry.attributes.normal;
  15253. const groups = geometry.groups;
  15254. const drawRange = geometry.drawRange;
  15255. if ( index !== null ) {
  15256. // indexed buffer geometry
  15257. if ( Array.isArray( material ) ) {
  15258. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15259. const group = groups[ i ];
  15260. const groupMaterial = material[ group.materialIndex ];
  15261. const start = Math.max( group.start, drawRange.start );
  15262. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15263. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15264. const a = index.getX( j );
  15265. const b = index.getX( j + 1 );
  15266. const c = index.getX( j + 2 );
  15267. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15268. if ( intersection ) {
  15269. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15270. intersection.face.materialIndex = group.materialIndex;
  15271. intersects.push( intersection );
  15272. }
  15273. }
  15274. }
  15275. } else {
  15276. const start = Math.max( 0, drawRange.start );
  15277. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15278. for ( let i = start, il = end; i < il; i += 3 ) {
  15279. const a = index.getX( i );
  15280. const b = index.getX( i + 1 );
  15281. const c = index.getX( i + 2 );
  15282. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15283. if ( intersection ) {
  15284. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15285. intersects.push( intersection );
  15286. }
  15287. }
  15288. }
  15289. } else if ( position !== undefined ) {
  15290. // non-indexed buffer geometry
  15291. if ( Array.isArray( material ) ) {
  15292. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15293. const group = groups[ i ];
  15294. const groupMaterial = material[ group.materialIndex ];
  15295. const start = Math.max( group.start, drawRange.start );
  15296. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15297. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15298. const a = j;
  15299. const b = j + 1;
  15300. const c = j + 2;
  15301. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15302. if ( intersection ) {
  15303. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15304. intersection.face.materialIndex = group.materialIndex;
  15305. intersects.push( intersection );
  15306. }
  15307. }
  15308. }
  15309. } else {
  15310. const start = Math.max( 0, drawRange.start );
  15311. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15312. for ( let i = start, il = end; i < il; i += 3 ) {
  15313. const a = i;
  15314. const b = i + 1;
  15315. const c = i + 2;
  15316. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15317. if ( intersection ) {
  15318. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15319. intersects.push( intersection );
  15320. }
  15321. }
  15322. }
  15323. }
  15324. }
  15325. }
  15326. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15327. let intersect;
  15328. if ( material.side === BackSide ) {
  15329. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15330. } else {
  15331. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15332. }
  15333. if ( intersect === null ) return null;
  15334. _intersectionPointWorld.copy( point );
  15335. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15336. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15337. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15338. return {
  15339. distance: distance,
  15340. point: _intersectionPointWorld.clone(),
  15341. object: object
  15342. };
  15343. }
  15344. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15345. object.getVertexPosition( a, _vA$1 );
  15346. object.getVertexPosition( b, _vB$1 );
  15347. object.getVertexPosition( c, _vC$1 );
  15348. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15349. if ( intersection ) {
  15350. const barycoord = new Vector3();
  15351. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15352. if ( uv ) {
  15353. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15354. }
  15355. if ( uv1 ) {
  15356. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15357. }
  15358. if ( normal ) {
  15359. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15360. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15361. intersection.normal.multiplyScalar( -1 );
  15362. }
  15363. }
  15364. const face = {
  15365. a: a,
  15366. b: b,
  15367. c: c,
  15368. normal: new Vector3(),
  15369. materialIndex: 0
  15370. };
  15371. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15372. intersection.face = face;
  15373. intersection.barycoord = barycoord;
  15374. }
  15375. return intersection;
  15376. }
  15377. /**
  15378. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15379. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15380. * of the axes.
  15381. *
  15382. * ```js
  15383. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15384. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15385. * const cube = new THREE.Mesh( geometry, material );
  15386. * scene.add( cube );
  15387. * ```
  15388. *
  15389. * @augments BufferGeometry
  15390. */
  15391. class BoxGeometry extends BufferGeometry {
  15392. /**
  15393. * Constructs a new box geometry.
  15394. *
  15395. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15396. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15397. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15398. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15399. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15400. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15401. */
  15402. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15403. super();
  15404. this.type = 'BoxGeometry';
  15405. /**
  15406. * Holds the constructor parameters that have been
  15407. * used to generate the geometry. Any modification
  15408. * after instantiation does not change the geometry.
  15409. *
  15410. * @type {Object}
  15411. */
  15412. this.parameters = {
  15413. width: width,
  15414. height: height,
  15415. depth: depth,
  15416. widthSegments: widthSegments,
  15417. heightSegments: heightSegments,
  15418. depthSegments: depthSegments
  15419. };
  15420. const scope = this;
  15421. // segments
  15422. widthSegments = Math.floor( widthSegments );
  15423. heightSegments = Math.floor( heightSegments );
  15424. depthSegments = Math.floor( depthSegments );
  15425. // buffers
  15426. const indices = [];
  15427. const vertices = [];
  15428. const normals = [];
  15429. const uvs = [];
  15430. // helper variables
  15431. let numberOfVertices = 0;
  15432. let groupStart = 0;
  15433. // build each side of the box geometry
  15434. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15435. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15436. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15437. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15438. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15439. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15440. // build geometry
  15441. this.setIndex( indices );
  15442. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15443. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15444. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15445. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15446. const segmentWidth = width / gridX;
  15447. const segmentHeight = height / gridY;
  15448. const widthHalf = width / 2;
  15449. const heightHalf = height / 2;
  15450. const depthHalf = depth / 2;
  15451. const gridX1 = gridX + 1;
  15452. const gridY1 = gridY + 1;
  15453. let vertexCounter = 0;
  15454. let groupCount = 0;
  15455. const vector = new Vector3();
  15456. // generate vertices, normals and uvs
  15457. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15458. const y = iy * segmentHeight - heightHalf;
  15459. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15460. const x = ix * segmentWidth - widthHalf;
  15461. // set values to correct vector component
  15462. vector[ u ] = x * udir;
  15463. vector[ v ] = y * vdir;
  15464. vector[ w ] = depthHalf;
  15465. // now apply vector to vertex buffer
  15466. vertices.push( vector.x, vector.y, vector.z );
  15467. // set values to correct vector component
  15468. vector[ u ] = 0;
  15469. vector[ v ] = 0;
  15470. vector[ w ] = depth > 0 ? 1 : -1;
  15471. // now apply vector to normal buffer
  15472. normals.push( vector.x, vector.y, vector.z );
  15473. // uvs
  15474. uvs.push( ix / gridX );
  15475. uvs.push( 1 - ( iy / gridY ) );
  15476. // counters
  15477. vertexCounter += 1;
  15478. }
  15479. }
  15480. // indices
  15481. // 1. you need three indices to draw a single face
  15482. // 2. a single segment consists of two faces
  15483. // 3. so we need to generate six (2*3) indices per segment
  15484. for ( let iy = 0; iy < gridY; iy ++ ) {
  15485. for ( let ix = 0; ix < gridX; ix ++ ) {
  15486. const a = numberOfVertices + ix + gridX1 * iy;
  15487. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15488. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15489. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15490. // faces
  15491. indices.push( a, b, d );
  15492. indices.push( b, c, d );
  15493. // increase counter
  15494. groupCount += 6;
  15495. }
  15496. }
  15497. // add a group to the geometry. this will ensure multi material support
  15498. scope.addGroup( groupStart, groupCount, materialIndex );
  15499. // calculate new start value for groups
  15500. groupStart += groupCount;
  15501. // update total number of vertices
  15502. numberOfVertices += vertexCounter;
  15503. }
  15504. }
  15505. copy( source ) {
  15506. super.copy( source );
  15507. this.parameters = Object.assign( {}, source.parameters );
  15508. return this;
  15509. }
  15510. /**
  15511. * Factory method for creating an instance of this class from the given
  15512. * JSON object.
  15513. *
  15514. * @param {Object} data - A JSON object representing the serialized geometry.
  15515. * @return {BoxGeometry} A new instance.
  15516. */
  15517. static fromJSON( data ) {
  15518. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15519. }
  15520. }
  15521. // Uniform Utilities
  15522. function cloneUniforms( src ) {
  15523. const dst = {};
  15524. for ( const u in src ) {
  15525. dst[ u ] = {};
  15526. for ( const p in src[ u ] ) {
  15527. const property = src[ u ][ p ];
  15528. if ( property && ( property.isColor ||
  15529. property.isMatrix3 || property.isMatrix4 ||
  15530. property.isVector2 || property.isVector3 || property.isVector4 ||
  15531. property.isTexture || property.isQuaternion ) ) {
  15532. if ( property.isRenderTargetTexture ) {
  15533. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15534. dst[ u ][ p ] = null;
  15535. } else {
  15536. dst[ u ][ p ] = property.clone();
  15537. }
  15538. } else if ( Array.isArray( property ) ) {
  15539. dst[ u ][ p ] = property.slice();
  15540. } else {
  15541. dst[ u ][ p ] = property;
  15542. }
  15543. }
  15544. }
  15545. return dst;
  15546. }
  15547. function mergeUniforms( uniforms ) {
  15548. const merged = {};
  15549. for ( let u = 0; u < uniforms.length; u ++ ) {
  15550. const tmp = cloneUniforms( uniforms[ u ] );
  15551. for ( const p in tmp ) {
  15552. merged[ p ] = tmp[ p ];
  15553. }
  15554. }
  15555. return merged;
  15556. }
  15557. function cloneUniformsGroups( src ) {
  15558. const dst = [];
  15559. for ( let u = 0; u < src.length; u ++ ) {
  15560. dst.push( src[ u ].clone() );
  15561. }
  15562. return dst;
  15563. }
  15564. function getUnlitUniformColorSpace( renderer ) {
  15565. const currentRenderTarget = renderer.getRenderTarget();
  15566. if ( currentRenderTarget === null ) {
  15567. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15568. return renderer.outputColorSpace;
  15569. }
  15570. // https://github.com/mrdoob/three.js/issues/27868
  15571. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15572. return currentRenderTarget.texture.colorSpace;
  15573. }
  15574. return ColorManagement.workingColorSpace;
  15575. }
  15576. // Legacy
  15577. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15578. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15579. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15580. /**
  15581. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15582. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15583. * effect not included with any of the built-in materials.
  15584. *
  15585. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15586. *
  15587. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15588. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15589. * you don't want that, use {@link RawShaderMaterial} instead.
  15590. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15591. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15592. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15593. * - The loop has to be [normalized]{@link https://en.wikipedia.org/wiki/Normalized_loop}.
  15594. * - The loop variable has to be *i*.
  15595. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15596. * value of *i* for the given iteration and can be used in preprocessor
  15597. * statements.
  15598. *
  15599. * ```js
  15600. * const material = new THREE.ShaderMaterial( {
  15601. * uniforms: {
  15602. * time: { value: 1.0 },
  15603. * resolution: { value: new THREE.Vector2() }
  15604. * },
  15605. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15606. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15607. * } );
  15608. * ```
  15609. *
  15610. * @augments Material
  15611. */
  15612. class ShaderMaterial extends Material {
  15613. /**
  15614. * Constructs a new shader material.
  15615. *
  15616. * @param {Object} [parameters] - An object with one or more properties
  15617. * defining the material's appearance. Any property of the material
  15618. * (including any property from inherited materials) can be passed
  15619. * in here. Color values can be passed any type of value accepted
  15620. * by {@link Color#set}.
  15621. */
  15622. constructor( parameters ) {
  15623. super();
  15624. /**
  15625. * This flag can be used for type testing.
  15626. *
  15627. * @type {boolean}
  15628. * @readonly
  15629. * @default true
  15630. */
  15631. this.isShaderMaterial = true;
  15632. this.type = 'ShaderMaterial';
  15633. /**
  15634. * Defines custom constants using `#define` directives within the GLSL code
  15635. * for both the vertex shader and the fragment shader; each key/value pair
  15636. * yields another directive.
  15637. * ```js
  15638. * defines: {
  15639. * FOO: 15,
  15640. * BAR: true
  15641. * }
  15642. * ```
  15643. * Yields the lines:
  15644. * ```
  15645. * #define FOO 15
  15646. * #define BAR true
  15647. * ```
  15648. *
  15649. * @type {Object}
  15650. */
  15651. this.defines = {};
  15652. /**
  15653. * An object of the form:
  15654. * ```js
  15655. * {
  15656. * "uniform1": { value: 1.0 },
  15657. * "uniform2": { value: 2 }
  15658. * }
  15659. * ```
  15660. * specifying the uniforms to be passed to the shader code; keys are uniform
  15661. * names, values are definitions of the form
  15662. * ```
  15663. * {
  15664. * value: 1.0
  15665. * }
  15666. * ```
  15667. * where `value` is the value of the uniform. Names must match the name of
  15668. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15669. * on every frame, so updating the value of the uniform will immediately
  15670. * update the value available to the GLSL code.
  15671. *
  15672. * @type {Object}
  15673. */
  15674. this.uniforms = {};
  15675. /**
  15676. * An array holding uniforms groups for configuring UBOs.
  15677. *
  15678. * @type {Array<UniformsGroup>}
  15679. */
  15680. this.uniformsGroups = [];
  15681. /**
  15682. * Vertex shader GLSL code. This is the actual code for the shader.
  15683. *
  15684. * @type {string}
  15685. */
  15686. this.vertexShader = default_vertex;
  15687. /**
  15688. * Fragment shader GLSL code. This is the actual code for the shader.
  15689. *
  15690. * @type {string}
  15691. */
  15692. this.fragmentShader = default_fragment;
  15693. /**
  15694. * Controls line thickness or lines.
  15695. *
  15696. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15697. * width of one pixel.
  15698. *
  15699. * @type {number}
  15700. * @default 1
  15701. */
  15702. this.linewidth = 1;
  15703. /**
  15704. * Renders the geometry as a wireframe.
  15705. *
  15706. * @type {boolean}
  15707. * @default false
  15708. */
  15709. this.wireframe = false;
  15710. /**
  15711. * Controls the thickness of the wireframe.
  15712. *
  15713. * WebGL and WebGPU ignore this property and always render
  15714. * 1 pixel wide lines.
  15715. *
  15716. * @type {number}
  15717. * @default 1
  15718. */
  15719. this.wireframeLinewidth = 1;
  15720. /**
  15721. * Define whether the material color is affected by global fog settings; `true`
  15722. * to pass fog uniforms to the shader.
  15723. *
  15724. * @type {boolean}
  15725. * @default false
  15726. */
  15727. this.fog = false;
  15728. /**
  15729. * Defines whether this material uses lighting; `true` to pass uniform data
  15730. * related to lighting to this shader.
  15731. *
  15732. * @type {boolean}
  15733. * @default false
  15734. */
  15735. this.lights = false;
  15736. /**
  15737. * Defines whether this material supports clipping; `true` to let the renderer
  15738. * pass the clippingPlanes uniform.
  15739. *
  15740. * @type {boolean}
  15741. * @default false
  15742. */
  15743. this.clipping = false;
  15744. /**
  15745. * Overwritten and set to `true` by default.
  15746. *
  15747. * @type {boolean}
  15748. * @default true
  15749. */
  15750. this.forceSinglePass = true;
  15751. /**
  15752. * This object allows to enable certain WebGL 2 extensions.
  15753. *
  15754. * - clipCullDistance: set to `true` to use vertex shader clipping
  15755. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15756. *
  15757. * @type {{clipCullDistance:false,multiDraw:false}}
  15758. */
  15759. this.extensions = {
  15760. clipCullDistance: false, // set to use vertex shader clipping
  15761. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15762. };
  15763. /**
  15764. * When the rendered geometry doesn't include these attributes but the
  15765. * material does, these default values will be passed to the shaders. This
  15766. * avoids errors when buffer data is missing.
  15767. *
  15768. * - color: [ 1, 1, 1 ]
  15769. * - uv: [ 0, 0 ]
  15770. * - uv1: [ 0, 0 ]
  15771. *
  15772. * @type {Object}
  15773. */
  15774. this.defaultAttributeValues = {
  15775. 'color': [ 1, 1, 1 ],
  15776. 'uv': [ 0, 0 ],
  15777. 'uv1': [ 0, 0 ]
  15778. };
  15779. /**
  15780. * If set, this calls [gl.bindAttribLocation]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation}
  15781. * to bind a generic vertex index to an attribute variable.
  15782. *
  15783. * @type {string|undefined}
  15784. * @default undefined
  15785. */
  15786. this.index0AttributeName = undefined;
  15787. /**
  15788. * Can be used to force a uniform update while changing uniforms in
  15789. * {@link Object3D#onBeforeRender}.
  15790. *
  15791. * @type {boolean}
  15792. * @default false
  15793. */
  15794. this.uniformsNeedUpdate = false;
  15795. /**
  15796. * Defines the GLSL version of custom shader code.
  15797. *
  15798. * @type {?(GLSL1|GLSL3)}
  15799. * @default null
  15800. */
  15801. this.glslVersion = null;
  15802. if ( parameters !== undefined ) {
  15803. this.setValues( parameters );
  15804. }
  15805. }
  15806. copy( source ) {
  15807. super.copy( source );
  15808. this.fragmentShader = source.fragmentShader;
  15809. this.vertexShader = source.vertexShader;
  15810. this.uniforms = cloneUniforms( source.uniforms );
  15811. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15812. this.defines = Object.assign( {}, source.defines );
  15813. this.wireframe = source.wireframe;
  15814. this.wireframeLinewidth = source.wireframeLinewidth;
  15815. this.fog = source.fog;
  15816. this.lights = source.lights;
  15817. this.clipping = source.clipping;
  15818. this.extensions = Object.assign( {}, source.extensions );
  15819. this.glslVersion = source.glslVersion;
  15820. return this;
  15821. }
  15822. toJSON( meta ) {
  15823. const data = super.toJSON( meta );
  15824. data.glslVersion = this.glslVersion;
  15825. data.uniforms = {};
  15826. for ( const name in this.uniforms ) {
  15827. const uniform = this.uniforms[ name ];
  15828. const value = uniform.value;
  15829. if ( value && value.isTexture ) {
  15830. data.uniforms[ name ] = {
  15831. type: 't',
  15832. value: value.toJSON( meta ).uuid
  15833. };
  15834. } else if ( value && value.isColor ) {
  15835. data.uniforms[ name ] = {
  15836. type: 'c',
  15837. value: value.getHex()
  15838. };
  15839. } else if ( value && value.isVector2 ) {
  15840. data.uniforms[ name ] = {
  15841. type: 'v2',
  15842. value: value.toArray()
  15843. };
  15844. } else if ( value && value.isVector3 ) {
  15845. data.uniforms[ name ] = {
  15846. type: 'v3',
  15847. value: value.toArray()
  15848. };
  15849. } else if ( value && value.isVector4 ) {
  15850. data.uniforms[ name ] = {
  15851. type: 'v4',
  15852. value: value.toArray()
  15853. };
  15854. } else if ( value && value.isMatrix3 ) {
  15855. data.uniforms[ name ] = {
  15856. type: 'm3',
  15857. value: value.toArray()
  15858. };
  15859. } else if ( value && value.isMatrix4 ) {
  15860. data.uniforms[ name ] = {
  15861. type: 'm4',
  15862. value: value.toArray()
  15863. };
  15864. } else {
  15865. data.uniforms[ name ] = {
  15866. value: value
  15867. };
  15868. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15869. }
  15870. }
  15871. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15872. data.vertexShader = this.vertexShader;
  15873. data.fragmentShader = this.fragmentShader;
  15874. data.lights = this.lights;
  15875. data.clipping = this.clipping;
  15876. const extensions = {};
  15877. for ( const key in this.extensions ) {
  15878. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15879. }
  15880. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15881. return data;
  15882. }
  15883. }
  15884. /**
  15885. * Abstract base class for cameras. This class should always be inherited
  15886. * when you build a new camera.
  15887. *
  15888. * @abstract
  15889. * @augments Object3D
  15890. */
  15891. class Camera extends Object3D {
  15892. /**
  15893. * Constructs a new camera.
  15894. */
  15895. constructor() {
  15896. super();
  15897. /**
  15898. * This flag can be used for type testing.
  15899. *
  15900. * @type {boolean}
  15901. * @readonly
  15902. * @default true
  15903. */
  15904. this.isCamera = true;
  15905. this.type = 'Camera';
  15906. /**
  15907. * The inverse of the camera's world matrix.
  15908. *
  15909. * @type {Matrix4}
  15910. */
  15911. this.matrixWorldInverse = new Matrix4();
  15912. /**
  15913. * The camera's projection matrix.
  15914. *
  15915. * @type {Matrix4}
  15916. */
  15917. this.projectionMatrix = new Matrix4();
  15918. /**
  15919. * The inverse of the camera's projection matrix.
  15920. *
  15921. * @type {Matrix4}
  15922. */
  15923. this.projectionMatrixInverse = new Matrix4();
  15924. /**
  15925. * The coordinate system in which the camera is used.
  15926. *
  15927. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  15928. */
  15929. this.coordinateSystem = WebGLCoordinateSystem;
  15930. this._reversedDepth = false;
  15931. }
  15932. /**
  15933. * The flag that indicates whether the camera uses a reversed depth buffer.
  15934. *
  15935. * @type {boolean}
  15936. * @default false
  15937. */
  15938. get reversedDepth() {
  15939. return this._reversedDepth;
  15940. }
  15941. copy( source, recursive ) {
  15942. super.copy( source, recursive );
  15943. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  15944. this.projectionMatrix.copy( source.projectionMatrix );
  15945. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  15946. this.coordinateSystem = source.coordinateSystem;
  15947. return this;
  15948. }
  15949. /**
  15950. * Returns a vector representing the ("look") direction of the 3D object in world space.
  15951. *
  15952. * This method is overwritten since cameras have a different forward vector compared to other
  15953. * 3D objects. A camera looks down its local, negative z-axis by default.
  15954. *
  15955. * @param {Vector3} target - The target vector the result is stored to.
  15956. * @return {Vector3} The 3D object's direction in world space.
  15957. */
  15958. getWorldDirection( target ) {
  15959. return super.getWorldDirection( target ).negate();
  15960. }
  15961. updateMatrixWorld( force ) {
  15962. super.updateMatrixWorld( force );
  15963. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15964. }
  15965. updateWorldMatrix( updateParents, updateChildren ) {
  15966. super.updateWorldMatrix( updateParents, updateChildren );
  15967. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15968. }
  15969. clone() {
  15970. return new this.constructor().copy( this );
  15971. }
  15972. }
  15973. const _v3$1 = /*@__PURE__*/ new Vector3();
  15974. const _minTarget = /*@__PURE__*/ new Vector2();
  15975. const _maxTarget = /*@__PURE__*/ new Vector2();
  15976. /**
  15977. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  15978. *
  15979. * This projection mode is designed to mimic the way the human eye sees. It
  15980. * is the most common projection mode used for rendering a 3D scene.
  15981. *
  15982. * ```js
  15983. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  15984. * scene.add( camera );
  15985. * ```
  15986. *
  15987. * @augments Camera
  15988. */
  15989. class PerspectiveCamera extends Camera {
  15990. /**
  15991. * Constructs a new perspective camera.
  15992. *
  15993. * @param {number} [fov=50] - The vertical field of view.
  15994. * @param {number} [aspect=1] - The aspect ratio.
  15995. * @param {number} [near=0.1] - The camera's near plane.
  15996. * @param {number} [far=2000] - The camera's far plane.
  15997. */
  15998. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  15999. super();
  16000. /**
  16001. * This flag can be used for type testing.
  16002. *
  16003. * @type {boolean}
  16004. * @readonly
  16005. * @default true
  16006. */
  16007. this.isPerspectiveCamera = true;
  16008. this.type = 'PerspectiveCamera';
  16009. /**
  16010. * The vertical field of view, from bottom to top of view,
  16011. * in degrees.
  16012. *
  16013. * @type {number}
  16014. * @default 50
  16015. */
  16016. this.fov = fov;
  16017. /**
  16018. * The zoom factor of the camera.
  16019. *
  16020. * @type {number}
  16021. * @default 1
  16022. */
  16023. this.zoom = 1;
  16024. /**
  16025. * The camera's near plane. The valid range is greater than `0`
  16026. * and less than the current value of {@link PerspectiveCamera#far}.
  16027. *
  16028. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16029. * valid value for a perspective camera's near plane.
  16030. *
  16031. * @type {number}
  16032. * @default 0.1
  16033. */
  16034. this.near = near;
  16035. /**
  16036. * The camera's far plane. Must be greater than the
  16037. * current value of {@link PerspectiveCamera#near}.
  16038. *
  16039. * @type {number}
  16040. * @default 2000
  16041. */
  16042. this.far = far;
  16043. /**
  16044. * Object distance used for stereoscopy and depth-of-field effects. This
  16045. * parameter does not influence the projection matrix unless a
  16046. * {@link StereoCamera} is being used.
  16047. *
  16048. * @type {number}
  16049. * @default 10
  16050. */
  16051. this.focus = 10;
  16052. /**
  16053. * The aspect ratio, usually the canvas width / canvas height.
  16054. *
  16055. * @type {number}
  16056. * @default 1
  16057. */
  16058. this.aspect = aspect;
  16059. /**
  16060. * Represents the frustum window specification. This property should not be edited
  16061. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16062. *
  16063. * @type {?Object}
  16064. * @default null
  16065. */
  16066. this.view = null;
  16067. /**
  16068. * Film size used for the larger axis. Default is `35` (millimeters). This
  16069. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16070. * is set to a nonzero value.
  16071. *
  16072. * @type {number}
  16073. * @default 35
  16074. */
  16075. this.filmGauge = 35;
  16076. /**
  16077. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16078. *
  16079. * @type {number}
  16080. * @default 0
  16081. */
  16082. this.filmOffset = 0;
  16083. this.updateProjectionMatrix();
  16084. }
  16085. copy( source, recursive ) {
  16086. super.copy( source, recursive );
  16087. this.fov = source.fov;
  16088. this.zoom = source.zoom;
  16089. this.near = source.near;
  16090. this.far = source.far;
  16091. this.focus = source.focus;
  16092. this.aspect = source.aspect;
  16093. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16094. this.filmGauge = source.filmGauge;
  16095. this.filmOffset = source.filmOffset;
  16096. return this;
  16097. }
  16098. /**
  16099. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16100. *
  16101. * The default film gauge is 35, so that the focal length can be specified for
  16102. * a 35mm (full frame) camera.
  16103. *
  16104. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16105. */
  16106. setFocalLength( focalLength ) {
  16107. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16108. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16109. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16110. this.updateProjectionMatrix();
  16111. }
  16112. /**
  16113. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16114. * {@link PerspectiveCamera#filmGauge}.
  16115. *
  16116. * @return {number} The computed focal length.
  16117. */
  16118. getFocalLength() {
  16119. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16120. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16121. }
  16122. /**
  16123. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16124. *
  16125. * @return {number} The effective FOV.
  16126. */
  16127. getEffectiveFOV() {
  16128. return RAD2DEG * 2 * Math.atan(
  16129. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16130. }
  16131. /**
  16132. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16133. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16134. *
  16135. * @return {number} The film width.
  16136. */
  16137. getFilmWidth() {
  16138. // film not completely covered in portrait format (aspect < 1)
  16139. return this.filmGauge * Math.min( this.aspect, 1 );
  16140. }
  16141. /**
  16142. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16143. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16144. *
  16145. * @return {number} The film width.
  16146. */
  16147. getFilmHeight() {
  16148. // film not completely covered in landscape format (aspect > 1)
  16149. return this.filmGauge / Math.max( this.aspect, 1 );
  16150. }
  16151. /**
  16152. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16153. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16154. *
  16155. * @param {number} distance - The viewing distance.
  16156. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16157. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16158. */
  16159. getViewBounds( distance, minTarget, maxTarget ) {
  16160. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16161. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16162. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16163. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16164. }
  16165. /**
  16166. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16167. *
  16168. * @param {number} distance - The viewing distance.
  16169. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16170. * @returns {Vector2} The view size.
  16171. */
  16172. getViewSize( distance, target ) {
  16173. this.getViewBounds( distance, _minTarget, _maxTarget );
  16174. return target.subVectors( _maxTarget, _minTarget );
  16175. }
  16176. /**
  16177. * Sets an offset in a larger frustum. This is useful for multi-window or
  16178. * multi-monitor/multi-machine setups.
  16179. *
  16180. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16181. * the monitors are in grid like this
  16182. *```
  16183. * +---+---+---+
  16184. * | A | B | C |
  16185. * +---+---+---+
  16186. * | D | E | F |
  16187. * +---+---+---+
  16188. *```
  16189. * then for each monitor you would call it like this:
  16190. *```js
  16191. * const w = 1920;
  16192. * const h = 1080;
  16193. * const fullWidth = w * 3;
  16194. * const fullHeight = h * 2;
  16195. *
  16196. * // --A--
  16197. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16198. * // --B--
  16199. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16200. * // --C--
  16201. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16202. * // --D--
  16203. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16204. * // --E--
  16205. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16206. * // --F--
  16207. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16208. * ```
  16209. *
  16210. * Note there is no reason monitors have to be the same size or in a grid.
  16211. *
  16212. * @param {number} fullWidth - The full width of multiview setup.
  16213. * @param {number} fullHeight - The full height of multiview setup.
  16214. * @param {number} x - The horizontal offset of the subcamera.
  16215. * @param {number} y - The vertical offset of the subcamera.
  16216. * @param {number} width - The width of subcamera.
  16217. * @param {number} height - The height of subcamera.
  16218. */
  16219. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16220. this.aspect = fullWidth / fullHeight;
  16221. if ( this.view === null ) {
  16222. this.view = {
  16223. enabled: true,
  16224. fullWidth: 1,
  16225. fullHeight: 1,
  16226. offsetX: 0,
  16227. offsetY: 0,
  16228. width: 1,
  16229. height: 1
  16230. };
  16231. }
  16232. this.view.enabled = true;
  16233. this.view.fullWidth = fullWidth;
  16234. this.view.fullHeight = fullHeight;
  16235. this.view.offsetX = x;
  16236. this.view.offsetY = y;
  16237. this.view.width = width;
  16238. this.view.height = height;
  16239. this.updateProjectionMatrix();
  16240. }
  16241. /**
  16242. * Removes the view offset from the projection matrix.
  16243. */
  16244. clearViewOffset() {
  16245. if ( this.view !== null ) {
  16246. this.view.enabled = false;
  16247. }
  16248. this.updateProjectionMatrix();
  16249. }
  16250. /**
  16251. * Updates the camera's projection matrix. Must be called after any change of
  16252. * camera properties.
  16253. */
  16254. updateProjectionMatrix() {
  16255. const near = this.near;
  16256. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16257. let height = 2 * top;
  16258. let width = this.aspect * height;
  16259. let left = -0.5 * width;
  16260. const view = this.view;
  16261. if ( this.view !== null && this.view.enabled ) {
  16262. const fullWidth = view.fullWidth,
  16263. fullHeight = view.fullHeight;
  16264. left += view.offsetX * width / fullWidth;
  16265. top -= view.offsetY * height / fullHeight;
  16266. width *= view.width / fullWidth;
  16267. height *= view.height / fullHeight;
  16268. }
  16269. const skew = this.filmOffset;
  16270. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16271. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16272. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16273. }
  16274. toJSON( meta ) {
  16275. const data = super.toJSON( meta );
  16276. data.object.fov = this.fov;
  16277. data.object.zoom = this.zoom;
  16278. data.object.near = this.near;
  16279. data.object.far = this.far;
  16280. data.object.focus = this.focus;
  16281. data.object.aspect = this.aspect;
  16282. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16283. data.object.filmGauge = this.filmGauge;
  16284. data.object.filmOffset = this.filmOffset;
  16285. return data;
  16286. }
  16287. }
  16288. const fov = -90; // negative fov is not an error
  16289. const aspect = 1;
  16290. /**
  16291. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16292. * cube render target. The render target can then be used as an environment map for rendering
  16293. * realtime reflections in your scene.
  16294. *
  16295. * ```js
  16296. * // Create cube render target
  16297. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16298. *
  16299. * // Create cube camera
  16300. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16301. * scene.add( cubeCamera );
  16302. *
  16303. * // Create car
  16304. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16305. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16306. * scene.add( car );
  16307. *
  16308. * // Update the render target cube
  16309. * car.visible = false;
  16310. * cubeCamera.position.copy( car.position );
  16311. * cubeCamera.update( renderer, scene );
  16312. *
  16313. * // Render the scene
  16314. * car.visible = true;
  16315. * renderer.render( scene, camera );
  16316. * ```
  16317. *
  16318. * @augments Object3D
  16319. */
  16320. class CubeCamera extends Object3D {
  16321. /**
  16322. * Constructs a new cube camera.
  16323. *
  16324. * @param {number} near - The camera's near plane.
  16325. * @param {number} far - The camera's far plane.
  16326. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16327. */
  16328. constructor( near, far, renderTarget ) {
  16329. super();
  16330. this.type = 'CubeCamera';
  16331. /**
  16332. * A reference to the cube render target.
  16333. *
  16334. * @type {WebGLCubeRenderTarget}
  16335. */
  16336. this.renderTarget = renderTarget;
  16337. /**
  16338. * The current active coordinate system.
  16339. *
  16340. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16341. * @default null
  16342. */
  16343. this.coordinateSystem = null;
  16344. /**
  16345. * The current active mipmap level
  16346. *
  16347. * @type {number}
  16348. * @default 0
  16349. */
  16350. this.activeMipmapLevel = 0;
  16351. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16352. cameraPX.layers = this.layers;
  16353. this.add( cameraPX );
  16354. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16355. cameraNX.layers = this.layers;
  16356. this.add( cameraNX );
  16357. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16358. cameraPY.layers = this.layers;
  16359. this.add( cameraPY );
  16360. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16361. cameraNY.layers = this.layers;
  16362. this.add( cameraNY );
  16363. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16364. cameraPZ.layers = this.layers;
  16365. this.add( cameraPZ );
  16366. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16367. cameraNZ.layers = this.layers;
  16368. this.add( cameraNZ );
  16369. }
  16370. /**
  16371. * Must be called when the coordinate system of the cube camera is changed.
  16372. */
  16373. updateCoordinateSystem() {
  16374. const coordinateSystem = this.coordinateSystem;
  16375. const cameras = this.children.concat();
  16376. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16377. for ( const camera of cameras ) this.remove( camera );
  16378. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16379. cameraPX.up.set( 0, 1, 0 );
  16380. cameraPX.lookAt( 1, 0, 0 );
  16381. cameraNX.up.set( 0, 1, 0 );
  16382. cameraNX.lookAt( -1, 0, 0 );
  16383. cameraPY.up.set( 0, 0, -1 );
  16384. cameraPY.lookAt( 0, 1, 0 );
  16385. cameraNY.up.set( 0, 0, 1 );
  16386. cameraNY.lookAt( 0, -1, 0 );
  16387. cameraPZ.up.set( 0, 1, 0 );
  16388. cameraPZ.lookAt( 0, 0, 1 );
  16389. cameraNZ.up.set( 0, 1, 0 );
  16390. cameraNZ.lookAt( 0, 0, -1 );
  16391. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16392. cameraPX.up.set( 0, -1, 0 );
  16393. cameraPX.lookAt( -1, 0, 0 );
  16394. cameraNX.up.set( 0, -1, 0 );
  16395. cameraNX.lookAt( 1, 0, 0 );
  16396. cameraPY.up.set( 0, 0, 1 );
  16397. cameraPY.lookAt( 0, 1, 0 );
  16398. cameraNY.up.set( 0, 0, -1 );
  16399. cameraNY.lookAt( 0, -1, 0 );
  16400. cameraPZ.up.set( 0, -1, 0 );
  16401. cameraPZ.lookAt( 0, 0, 1 );
  16402. cameraNZ.up.set( 0, -1, 0 );
  16403. cameraNZ.lookAt( 0, 0, -1 );
  16404. } else {
  16405. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16406. }
  16407. for ( const camera of cameras ) {
  16408. this.add( camera );
  16409. camera.updateMatrixWorld();
  16410. }
  16411. }
  16412. /**
  16413. * Calling this method will render the given scene with the given renderer
  16414. * into the cube render target of the camera.
  16415. *
  16416. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16417. * @param {Scene} scene - The scene to render.
  16418. */
  16419. update( renderer, scene ) {
  16420. if ( this.parent === null ) this.updateMatrixWorld();
  16421. const { renderTarget, activeMipmapLevel } = this;
  16422. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16423. this.coordinateSystem = renderer.coordinateSystem;
  16424. this.updateCoordinateSystem();
  16425. }
  16426. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16427. const currentRenderTarget = renderer.getRenderTarget();
  16428. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16429. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16430. const currentXrEnabled = renderer.xr.enabled;
  16431. renderer.xr.enabled = false;
  16432. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16433. renderTarget.texture.generateMipmaps = false;
  16434. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16435. renderer.render( scene, cameraPX );
  16436. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16437. renderer.render( scene, cameraNX );
  16438. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16439. renderer.render( scene, cameraPY );
  16440. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16441. renderer.render( scene, cameraNY );
  16442. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16443. renderer.render( scene, cameraPZ );
  16444. // mipmaps are generated during the last call of render()
  16445. // at this point, all sides of the cube render target are defined
  16446. renderTarget.texture.generateMipmaps = generateMipmaps;
  16447. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16448. renderer.render( scene, cameraNZ );
  16449. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16450. renderer.xr.enabled = currentXrEnabled;
  16451. renderTarget.texture.needsPMREMUpdate = true;
  16452. }
  16453. }
  16454. /**
  16455. * Creates a cube texture made up of six images.
  16456. *
  16457. * ```js
  16458. * const loader = new THREE.CubeTextureLoader();
  16459. * loader.setPath( 'textures/cube/pisa/' );
  16460. *
  16461. * const textureCube = loader.load( [
  16462. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16463. * ] );
  16464. *
  16465. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16466. * ```
  16467. *
  16468. * @augments Texture
  16469. */
  16470. class CubeTexture extends Texture {
  16471. /**
  16472. * Constructs a new cube texture.
  16473. *
  16474. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16475. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16476. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16477. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16478. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16479. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16480. * @param {number} [format=RGBAFormat] - The texture format.
  16481. * @param {number} [type=UnsignedByteType] - The texture type.
  16482. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16483. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16484. */
  16485. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16486. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16487. /**
  16488. * This flag can be used for type testing.
  16489. *
  16490. * @type {boolean}
  16491. * @readonly
  16492. * @default true
  16493. */
  16494. this.isCubeTexture = true;
  16495. /**
  16496. * If set to `true`, the texture is flipped along the vertical axis when
  16497. * uploaded to the GPU.
  16498. *
  16499. * Overwritten and set to `false` by default.
  16500. *
  16501. * @type {boolean}
  16502. * @default false
  16503. */
  16504. this.flipY = false;
  16505. }
  16506. /**
  16507. * Alias for {@link CubeTexture#image}.
  16508. *
  16509. * @type {Array<Image>}
  16510. */
  16511. get images() {
  16512. return this.image;
  16513. }
  16514. set images( value ) {
  16515. this.image = value;
  16516. }
  16517. }
  16518. /**
  16519. * A cube render target used in context of {@link WebGLRenderer}.
  16520. *
  16521. * @augments WebGLRenderTarget
  16522. */
  16523. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16524. /**
  16525. * Constructs a new cube render target.
  16526. *
  16527. * @param {number} [size=1] - The size of the render target.
  16528. * @param {RenderTarget~Options} [options] - The configuration object.
  16529. */
  16530. constructor( size = 1, options = {} ) {
  16531. super( size, size, options );
  16532. /**
  16533. * This flag can be used for type testing.
  16534. *
  16535. * @type {boolean}
  16536. * @readonly
  16537. * @default true
  16538. */
  16539. this.isWebGLCubeRenderTarget = true;
  16540. const image = { width: size, height: size, depth: 1 };
  16541. const images = [ image, image, image, image, image, image ];
  16542. /**
  16543. * Overwritten with a different texture type.
  16544. *
  16545. * @type {DataArrayTexture}
  16546. */
  16547. this.texture = new CubeTexture( images );
  16548. this._setTextureOptions( options );
  16549. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16550. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16551. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16552. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16553. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16554. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16555. this.texture.isRenderTargetTexture = true;
  16556. }
  16557. /**
  16558. * Converts the given equirectangular texture to a cube map.
  16559. *
  16560. * @param {WebGLRenderer} renderer - The renderer.
  16561. * @param {Texture} texture - The equirectangular texture.
  16562. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16563. */
  16564. fromEquirectangularTexture( renderer, texture ) {
  16565. this.texture.type = texture.type;
  16566. this.texture.colorSpace = texture.colorSpace;
  16567. this.texture.generateMipmaps = texture.generateMipmaps;
  16568. this.texture.minFilter = texture.minFilter;
  16569. this.texture.magFilter = texture.magFilter;
  16570. const shader = {
  16571. uniforms: {
  16572. tEquirect: { value: null },
  16573. },
  16574. vertexShader: /* glsl */`
  16575. varying vec3 vWorldDirection;
  16576. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16577. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16578. }
  16579. void main() {
  16580. vWorldDirection = transformDirection( position, modelMatrix );
  16581. #include <begin_vertex>
  16582. #include <project_vertex>
  16583. }
  16584. `,
  16585. fragmentShader: /* glsl */`
  16586. uniform sampler2D tEquirect;
  16587. varying vec3 vWorldDirection;
  16588. #include <common>
  16589. void main() {
  16590. vec3 direction = normalize( vWorldDirection );
  16591. vec2 sampleUV = equirectUv( direction );
  16592. gl_FragColor = texture2D( tEquirect, sampleUV );
  16593. }
  16594. `
  16595. };
  16596. const geometry = new BoxGeometry( 5, 5, 5 );
  16597. const material = new ShaderMaterial( {
  16598. name: 'CubemapFromEquirect',
  16599. uniforms: cloneUniforms( shader.uniforms ),
  16600. vertexShader: shader.vertexShader,
  16601. fragmentShader: shader.fragmentShader,
  16602. side: BackSide,
  16603. blending: NoBlending
  16604. } );
  16605. material.uniforms.tEquirect.value = texture;
  16606. const mesh = new Mesh( geometry, material );
  16607. const currentMinFilter = texture.minFilter;
  16608. // Avoid blurred poles
  16609. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16610. const camera = new CubeCamera( 1, 10, this );
  16611. camera.update( renderer, mesh );
  16612. texture.minFilter = currentMinFilter;
  16613. mesh.geometry.dispose();
  16614. mesh.material.dispose();
  16615. return this;
  16616. }
  16617. /**
  16618. * Clears this cube render target.
  16619. *
  16620. * @param {WebGLRenderer} renderer - The renderer.
  16621. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16622. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16623. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16624. */
  16625. clear( renderer, color = true, depth = true, stencil = true ) {
  16626. const currentRenderTarget = renderer.getRenderTarget();
  16627. for ( let i = 0; i < 6; i ++ ) {
  16628. renderer.setRenderTarget( this, i );
  16629. renderer.clear( color, depth, stencil );
  16630. }
  16631. renderer.setRenderTarget( currentRenderTarget );
  16632. }
  16633. }
  16634. /**
  16635. * This is almost identical to an {@link Object3D}. Its purpose is to
  16636. * make working with groups of objects syntactically clearer.
  16637. *
  16638. * ```js
  16639. * // Create a group and add the two cubes.
  16640. * // These cubes can now be rotated / scaled etc as a group.
  16641. * const group = new THREE.Group();
  16642. *
  16643. * group.add( meshA );
  16644. * group.add( meshB );
  16645. *
  16646. * scene.add( group );
  16647. * ```
  16648. *
  16649. * @augments Object3D
  16650. */
  16651. class Group extends Object3D {
  16652. constructor() {
  16653. super();
  16654. /**
  16655. * This flag can be used for type testing.
  16656. *
  16657. * @type {boolean}
  16658. * @readonly
  16659. * @default true
  16660. */
  16661. this.isGroup = true;
  16662. this.type = 'Group';
  16663. }
  16664. }
  16665. const _moveEvent = { type: 'move' };
  16666. /**
  16667. * Class for representing a XR controller with its
  16668. * different coordinate systems.
  16669. *
  16670. * @private
  16671. */
  16672. class WebXRController {
  16673. /**
  16674. * Constructs a new XR controller.
  16675. */
  16676. constructor() {
  16677. /**
  16678. * A group representing the target ray space
  16679. * of the XR controller.
  16680. *
  16681. * @private
  16682. * @type {?Group}
  16683. * @default null
  16684. */
  16685. this._targetRay = null;
  16686. /**
  16687. * A group representing the grip space
  16688. * of the XR controller.
  16689. *
  16690. * @private
  16691. * @type {?Group}
  16692. * @default null
  16693. */
  16694. this._grip = null;
  16695. /**
  16696. * A group representing the hand space
  16697. * of the XR controller.
  16698. *
  16699. * @private
  16700. * @type {?Group}
  16701. * @default null
  16702. */
  16703. this._hand = null;
  16704. }
  16705. /**
  16706. * Returns a group representing the hand space of the XR controller.
  16707. *
  16708. * @return {Group} A group representing the hand space of the XR controller.
  16709. */
  16710. getHandSpace() {
  16711. if ( this._hand === null ) {
  16712. this._hand = new Group();
  16713. this._hand.matrixAutoUpdate = false;
  16714. this._hand.visible = false;
  16715. this._hand.joints = {};
  16716. this._hand.inputState = { pinching: false };
  16717. }
  16718. return this._hand;
  16719. }
  16720. /**
  16721. * Returns a group representing the target ray space of the XR controller.
  16722. *
  16723. * @return {Group} A group representing the target ray space of the XR controller.
  16724. */
  16725. getTargetRaySpace() {
  16726. if ( this._targetRay === null ) {
  16727. this._targetRay = new Group();
  16728. this._targetRay.matrixAutoUpdate = false;
  16729. this._targetRay.visible = false;
  16730. this._targetRay.hasLinearVelocity = false;
  16731. this._targetRay.linearVelocity = new Vector3();
  16732. this._targetRay.hasAngularVelocity = false;
  16733. this._targetRay.angularVelocity = new Vector3();
  16734. }
  16735. return this._targetRay;
  16736. }
  16737. /**
  16738. * Returns a group representing the grip space of the XR controller.
  16739. *
  16740. * @return {Group} A group representing the grip space of the XR controller.
  16741. */
  16742. getGripSpace() {
  16743. if ( this._grip === null ) {
  16744. this._grip = new Group();
  16745. this._grip.matrixAutoUpdate = false;
  16746. this._grip.visible = false;
  16747. this._grip.hasLinearVelocity = false;
  16748. this._grip.linearVelocity = new Vector3();
  16749. this._grip.hasAngularVelocity = false;
  16750. this._grip.angularVelocity = new Vector3();
  16751. }
  16752. return this._grip;
  16753. }
  16754. /**
  16755. * Dispatches the given event to the groups representing
  16756. * the different coordinate spaces of the XR controller.
  16757. *
  16758. * @param {Object} event - The event to dispatch.
  16759. * @return {WebXRController} A reference to this instance.
  16760. */
  16761. dispatchEvent( event ) {
  16762. if ( this._targetRay !== null ) {
  16763. this._targetRay.dispatchEvent( event );
  16764. }
  16765. if ( this._grip !== null ) {
  16766. this._grip.dispatchEvent( event );
  16767. }
  16768. if ( this._hand !== null ) {
  16769. this._hand.dispatchEvent( event );
  16770. }
  16771. return this;
  16772. }
  16773. /**
  16774. * Connects the controller with the given XR input source.
  16775. *
  16776. * @param {XRInputSource} inputSource - The input source.
  16777. * @return {WebXRController} A reference to this instance.
  16778. */
  16779. connect( inputSource ) {
  16780. if ( inputSource && inputSource.hand ) {
  16781. const hand = this._hand;
  16782. if ( hand ) {
  16783. for ( const inputjoint of inputSource.hand.values() ) {
  16784. // Initialize hand with joints when connected
  16785. this._getHandJoint( hand, inputjoint );
  16786. }
  16787. }
  16788. }
  16789. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16790. return this;
  16791. }
  16792. /**
  16793. * Disconnects the controller from the given XR input source.
  16794. *
  16795. * @param {XRInputSource} inputSource - The input source.
  16796. * @return {WebXRController} A reference to this instance.
  16797. */
  16798. disconnect( inputSource ) {
  16799. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16800. if ( this._targetRay !== null ) {
  16801. this._targetRay.visible = false;
  16802. }
  16803. if ( this._grip !== null ) {
  16804. this._grip.visible = false;
  16805. }
  16806. if ( this._hand !== null ) {
  16807. this._hand.visible = false;
  16808. }
  16809. return this;
  16810. }
  16811. /**
  16812. * Updates the controller with the given input source, XR frame and reference space.
  16813. * This updates the transformations of the groups that represent the different
  16814. * coordinate systems of the controller.
  16815. *
  16816. * @param {XRInputSource} inputSource - The input source.
  16817. * @param {XRFrame} frame - The XR frame.
  16818. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16819. * @return {WebXRController} A reference to this instance.
  16820. */
  16821. update( inputSource, frame, referenceSpace ) {
  16822. let inputPose = null;
  16823. let gripPose = null;
  16824. let handPose = null;
  16825. const targetRay = this._targetRay;
  16826. const grip = this._grip;
  16827. const hand = this._hand;
  16828. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16829. if ( hand && inputSource.hand ) {
  16830. handPose = true;
  16831. for ( const inputjoint of inputSource.hand.values() ) {
  16832. // Update the joints groups with the XRJoint poses
  16833. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16834. // The transform of this joint will be updated with the joint pose on each frame
  16835. const joint = this._getHandJoint( hand, inputjoint );
  16836. if ( jointPose !== null ) {
  16837. joint.matrix.fromArray( jointPose.transform.matrix );
  16838. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16839. joint.matrixWorldNeedsUpdate = true;
  16840. joint.jointRadius = jointPose.radius;
  16841. }
  16842. joint.visible = jointPose !== null;
  16843. }
  16844. // Custom events
  16845. // Check pinchz
  16846. const indexTip = hand.joints[ 'index-finger-tip' ];
  16847. const thumbTip = hand.joints[ 'thumb-tip' ];
  16848. const distance = indexTip.position.distanceTo( thumbTip.position );
  16849. const distanceToPinch = 0.02;
  16850. const threshold = 0.005;
  16851. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16852. hand.inputState.pinching = false;
  16853. this.dispatchEvent( {
  16854. type: 'pinchend',
  16855. handedness: inputSource.handedness,
  16856. target: this
  16857. } );
  16858. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16859. hand.inputState.pinching = true;
  16860. this.dispatchEvent( {
  16861. type: 'pinchstart',
  16862. handedness: inputSource.handedness,
  16863. target: this
  16864. } );
  16865. }
  16866. } else {
  16867. if ( grip !== null && inputSource.gripSpace ) {
  16868. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16869. if ( gripPose !== null ) {
  16870. grip.matrix.fromArray( gripPose.transform.matrix );
  16871. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16872. grip.matrixWorldNeedsUpdate = true;
  16873. if ( gripPose.linearVelocity ) {
  16874. grip.hasLinearVelocity = true;
  16875. grip.linearVelocity.copy( gripPose.linearVelocity );
  16876. } else {
  16877. grip.hasLinearVelocity = false;
  16878. }
  16879. if ( gripPose.angularVelocity ) {
  16880. grip.hasAngularVelocity = true;
  16881. grip.angularVelocity.copy( gripPose.angularVelocity );
  16882. } else {
  16883. grip.hasAngularVelocity = false;
  16884. }
  16885. }
  16886. }
  16887. }
  16888. if ( targetRay !== null ) {
  16889. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16890. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16891. if ( inputPose === null && gripPose !== null ) {
  16892. inputPose = gripPose;
  16893. }
  16894. if ( inputPose !== null ) {
  16895. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16896. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16897. targetRay.matrixWorldNeedsUpdate = true;
  16898. if ( inputPose.linearVelocity ) {
  16899. targetRay.hasLinearVelocity = true;
  16900. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16901. } else {
  16902. targetRay.hasLinearVelocity = false;
  16903. }
  16904. if ( inputPose.angularVelocity ) {
  16905. targetRay.hasAngularVelocity = true;
  16906. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16907. } else {
  16908. targetRay.hasAngularVelocity = false;
  16909. }
  16910. this.dispatchEvent( _moveEvent );
  16911. }
  16912. }
  16913. }
  16914. if ( targetRay !== null ) {
  16915. targetRay.visible = ( inputPose !== null );
  16916. }
  16917. if ( grip !== null ) {
  16918. grip.visible = ( gripPose !== null );
  16919. }
  16920. if ( hand !== null ) {
  16921. hand.visible = ( handPose !== null );
  16922. }
  16923. return this;
  16924. }
  16925. /**
  16926. * Returns a group representing the hand joint for the given input joint.
  16927. *
  16928. * @private
  16929. * @param {Group} hand - The group representing the hand space.
  16930. * @param {XRJointSpace} inputjoint - The hand joint data.
  16931. * @return {Group} A group representing the hand joint for the given input joint.
  16932. */
  16933. _getHandJoint( hand, inputjoint ) {
  16934. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16935. const joint = new Group();
  16936. joint.matrixAutoUpdate = false;
  16937. joint.visible = false;
  16938. hand.joints[ inputjoint.jointName ] = joint;
  16939. hand.add( joint );
  16940. }
  16941. return hand.joints[ inputjoint.jointName ];
  16942. }
  16943. }
  16944. /**
  16945. * This class can be used to define an exponential squared fog,
  16946. * which gives a clear view near the camera and a faster than exponentially
  16947. * densening fog farther from the camera.
  16948. *
  16949. * ```js
  16950. * const scene = new THREE.Scene();
  16951. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  16952. * ```
  16953. */
  16954. class FogExp2 {
  16955. /**
  16956. * Constructs a new fog.
  16957. *
  16958. * @param {number|Color} color - The fog's color.
  16959. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  16960. */
  16961. constructor( color, density = 0.00025 ) {
  16962. /**
  16963. * This flag can be used for type testing.
  16964. *
  16965. * @type {boolean}
  16966. * @readonly
  16967. * @default true
  16968. */
  16969. this.isFogExp2 = true;
  16970. /**
  16971. * The name of the fog.
  16972. *
  16973. * @type {string}
  16974. */
  16975. this.name = '';
  16976. /**
  16977. * The fog's color.
  16978. *
  16979. * @type {Color}
  16980. */
  16981. this.color = new Color( color );
  16982. /**
  16983. * Defines how fast the fog will grow dense.
  16984. *
  16985. * @type {number}
  16986. * @default 0.00025
  16987. */
  16988. this.density = density;
  16989. }
  16990. /**
  16991. * Returns a new fog with copied values from this instance.
  16992. *
  16993. * @return {FogExp2} A clone of this instance.
  16994. */
  16995. clone() {
  16996. return new FogExp2( this.color, this.density );
  16997. }
  16998. /**
  16999. * Serializes the fog into JSON.
  17000. *
  17001. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17002. * @return {Object} A JSON object representing the serialized fog
  17003. */
  17004. toJSON( /* meta */ ) {
  17005. return {
  17006. type: 'FogExp2',
  17007. name: this.name,
  17008. color: this.color.getHex(),
  17009. density: this.density
  17010. };
  17011. }
  17012. }
  17013. /**
  17014. * This class can be used to define a linear fog that grows linearly denser
  17015. * with the distance.
  17016. *
  17017. * ```js
  17018. * const scene = new THREE.Scene();
  17019. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17020. * ```
  17021. */
  17022. class Fog {
  17023. /**
  17024. * Constructs a new fog.
  17025. *
  17026. * @param {number|Color} color - The fog's color.
  17027. * @param {number} [near=1] - The minimum distance to start applying fog.
  17028. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17029. */
  17030. constructor( color, near = 1, far = 1000 ) {
  17031. /**
  17032. * This flag can be used for type testing.
  17033. *
  17034. * @type {boolean}
  17035. * @readonly
  17036. * @default true
  17037. */
  17038. this.isFog = true;
  17039. /**
  17040. * The name of the fog.
  17041. *
  17042. * @type {string}
  17043. */
  17044. this.name = '';
  17045. /**
  17046. * The fog's color.
  17047. *
  17048. * @type {Color}
  17049. */
  17050. this.color = new Color( color );
  17051. /**
  17052. * The minimum distance to start applying fog. Objects that are less than
  17053. * `near` units from the active camera won't be affected by fog.
  17054. *
  17055. * @type {number}
  17056. * @default 1
  17057. */
  17058. this.near = near;
  17059. /**
  17060. * The maximum distance at which fog stops being calculated and applied.
  17061. * Objects that are more than `far` units away from the active camera won't
  17062. * be affected by fog.
  17063. *
  17064. * @type {number}
  17065. * @default 1000
  17066. */
  17067. this.far = far;
  17068. }
  17069. /**
  17070. * Returns a new fog with copied values from this instance.
  17071. *
  17072. * @return {Fog} A clone of this instance.
  17073. */
  17074. clone() {
  17075. return new Fog( this.color, this.near, this.far );
  17076. }
  17077. /**
  17078. * Serializes the fog into JSON.
  17079. *
  17080. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17081. * @return {Object} A JSON object representing the serialized fog
  17082. */
  17083. toJSON( /* meta */ ) {
  17084. return {
  17085. type: 'Fog',
  17086. name: this.name,
  17087. color: this.color.getHex(),
  17088. near: this.near,
  17089. far: this.far
  17090. };
  17091. }
  17092. }
  17093. /**
  17094. * Scenes allow you to set up what is to be rendered and where by three.js.
  17095. * This is where you place 3D objects like meshes, lines or lights.
  17096. *
  17097. * @augments Object3D
  17098. */
  17099. class Scene extends Object3D {
  17100. /**
  17101. * Constructs a new scene.
  17102. */
  17103. constructor() {
  17104. super();
  17105. /**
  17106. * This flag can be used for type testing.
  17107. *
  17108. * @type {boolean}
  17109. * @readonly
  17110. * @default true
  17111. */
  17112. this.isScene = true;
  17113. this.type = 'Scene';
  17114. /**
  17115. * Defines the background of the scene. Valid inputs are:
  17116. *
  17117. * - A color for defining a uniform colored background.
  17118. * - A texture for defining a (flat) textured background.
  17119. * - Cube textures or equirectangular textures for defining a skybox.
  17120. *
  17121. * @type {?(Color|Texture)}
  17122. * @default null
  17123. */
  17124. this.background = null;
  17125. /**
  17126. * Sets the environment map for all physical materials in the scene. However,
  17127. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17128. * material property.
  17129. *
  17130. * @type {?Texture}
  17131. * @default null
  17132. */
  17133. this.environment = null;
  17134. /**
  17135. * A fog instance defining the type of fog that affects everything
  17136. * rendered in the scene.
  17137. *
  17138. * @type {?(Fog|FogExp2)}
  17139. * @default null
  17140. */
  17141. this.fog = null;
  17142. /**
  17143. * Sets the blurriness of the background. Only influences environment maps
  17144. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17145. * and `1`.
  17146. *
  17147. * @type {number}
  17148. * @default 0
  17149. */
  17150. this.backgroundBlurriness = 0;
  17151. /**
  17152. * Attenuates the color of the background. Only applies to background textures.
  17153. *
  17154. * @type {number}
  17155. * @default 1
  17156. */
  17157. this.backgroundIntensity = 1;
  17158. /**
  17159. * The rotation of the background in radians. Only influences environment maps
  17160. * assigned to {@link Scene#background}.
  17161. *
  17162. * @type {Euler}
  17163. * @default (0,0,0)
  17164. */
  17165. this.backgroundRotation = new Euler();
  17166. /**
  17167. * Attenuates the color of the environment. Only influences environment maps
  17168. * assigned to {@link Scene#environment}.
  17169. *
  17170. * @type {number}
  17171. * @default 1
  17172. */
  17173. this.environmentIntensity = 1;
  17174. /**
  17175. * The rotation of the environment map in radians. Only influences physical materials
  17176. * in the scene when {@link Scene#environment} is used.
  17177. *
  17178. * @type {Euler}
  17179. * @default (0,0,0)
  17180. */
  17181. this.environmentRotation = new Euler();
  17182. /**
  17183. * Forces everything in the scene to be rendered with the defined material. It is possible
  17184. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17185. *
  17186. * @type {?Material}
  17187. * @default null
  17188. */
  17189. this.overrideMaterial = null;
  17190. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17191. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17192. }
  17193. }
  17194. copy( source, recursive ) {
  17195. super.copy( source, recursive );
  17196. if ( source.background !== null ) this.background = source.background.clone();
  17197. if ( source.environment !== null ) this.environment = source.environment.clone();
  17198. if ( source.fog !== null ) this.fog = source.fog.clone();
  17199. this.backgroundBlurriness = source.backgroundBlurriness;
  17200. this.backgroundIntensity = source.backgroundIntensity;
  17201. this.backgroundRotation.copy( source.backgroundRotation );
  17202. this.environmentIntensity = source.environmentIntensity;
  17203. this.environmentRotation.copy( source.environmentRotation );
  17204. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17205. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17206. return this;
  17207. }
  17208. toJSON( meta ) {
  17209. const data = super.toJSON( meta );
  17210. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17211. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17212. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17213. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17214. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17215. data.object.environmentRotation = this.environmentRotation.toArray();
  17216. return data;
  17217. }
  17218. }
  17219. /**
  17220. * "Interleaved" means that multiple attributes, possibly of different types,
  17221. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17222. *
  17223. * An introduction into interleaved arrays can be found here: [Interleaved array basics]{@link https://blog.tojicode.com/2011/05/interleaved-array-basics.html}
  17224. */
  17225. class InterleavedBuffer {
  17226. /**
  17227. * Constructs a new interleaved buffer.
  17228. *
  17229. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17230. * @param {number} stride - The number of typed-array elements per vertex.
  17231. */
  17232. constructor( array, stride ) {
  17233. /**
  17234. * This flag can be used for type testing.
  17235. *
  17236. * @type {boolean}
  17237. * @readonly
  17238. * @default true
  17239. */
  17240. this.isInterleavedBuffer = true;
  17241. /**
  17242. * A typed array with a shared buffer storing attribute data.
  17243. *
  17244. * @type {TypedArray}
  17245. */
  17246. this.array = array;
  17247. /**
  17248. * The number of typed-array elements per vertex.
  17249. *
  17250. * @type {number}
  17251. */
  17252. this.stride = stride;
  17253. /**
  17254. * The total number of elements in the array
  17255. *
  17256. * @type {number}
  17257. * @readonly
  17258. */
  17259. this.count = array !== undefined ? array.length / stride : 0;
  17260. /**
  17261. * Defines the intended usage pattern of the data store for optimization purposes.
  17262. *
  17263. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17264. * instantiate a new one and set the desired usage before the next render.
  17265. *
  17266. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17267. * @default StaticDrawUsage
  17268. */
  17269. this.usage = StaticDrawUsage;
  17270. /**
  17271. * This can be used to only update some components of stored vectors (for example, just the
  17272. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17273. *
  17274. * @type {Array<Object>}
  17275. */
  17276. this.updateRanges = [];
  17277. /**
  17278. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17279. *
  17280. * @type {number}
  17281. */
  17282. this.version = 0;
  17283. /**
  17284. * The UUID of the interleaved buffer.
  17285. *
  17286. * @type {string}
  17287. * @readonly
  17288. */
  17289. this.uuid = generateUUID();
  17290. }
  17291. /**
  17292. * A callback function that is executed after the renderer has transferred the attribute array
  17293. * data to the GPU.
  17294. */
  17295. onUploadCallback() {}
  17296. /**
  17297. * Flag to indicate that this attribute has changed and should be re-sent to
  17298. * the GPU. Set this to `true` when you modify the value of the array.
  17299. *
  17300. * @type {number}
  17301. * @default false
  17302. * @param {boolean} value
  17303. */
  17304. set needsUpdate( value ) {
  17305. if ( value === true ) this.version ++;
  17306. }
  17307. /**
  17308. * Sets the usage of this interleaved buffer.
  17309. *
  17310. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17311. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17312. */
  17313. setUsage( value ) {
  17314. this.usage = value;
  17315. return this;
  17316. }
  17317. /**
  17318. * Adds a range of data in the data array to be updated on the GPU.
  17319. *
  17320. * @param {number} start - Position at which to start update.
  17321. * @param {number} count - The number of components to update.
  17322. */
  17323. addUpdateRange( start, count ) {
  17324. this.updateRanges.push( { start, count } );
  17325. }
  17326. /**
  17327. * Clears the update ranges.
  17328. */
  17329. clearUpdateRanges() {
  17330. this.updateRanges.length = 0;
  17331. }
  17332. /**
  17333. * Copies the values of the given interleaved buffer to this instance.
  17334. *
  17335. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17336. * @return {InterleavedBuffer} A reference to this instance.
  17337. */
  17338. copy( source ) {
  17339. this.array = new source.array.constructor( source.array );
  17340. this.count = source.count;
  17341. this.stride = source.stride;
  17342. this.usage = source.usage;
  17343. return this;
  17344. }
  17345. /**
  17346. * Copies a vector from the given interleaved buffer to this one. The start
  17347. * and destination position in the attribute buffers are represented by the
  17348. * given indices.
  17349. *
  17350. * @param {number} index1 - The destination index into this interleaved buffer.
  17351. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17352. * @param {number} index2 - The source index into the given interleaved buffer.
  17353. * @return {InterleavedBuffer} A reference to this instance.
  17354. */
  17355. copyAt( index1, interleavedBuffer, index2 ) {
  17356. index1 *= this.stride;
  17357. index2 *= interleavedBuffer.stride;
  17358. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17359. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17360. }
  17361. return this;
  17362. }
  17363. /**
  17364. * Sets the given array data in the interleaved buffer.
  17365. *
  17366. * @param {(TypedArray|Array)} value - The array data to set.
  17367. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17368. * @return {InterleavedBuffer} A reference to this instance.
  17369. */
  17370. set( value, offset = 0 ) {
  17371. this.array.set( value, offset );
  17372. return this;
  17373. }
  17374. /**
  17375. * Returns a new interleaved buffer with copied values from this instance.
  17376. *
  17377. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17378. * @return {InterleavedBuffer} A clone of this instance.
  17379. */
  17380. clone( data ) {
  17381. if ( data.arrayBuffers === undefined ) {
  17382. data.arrayBuffers = {};
  17383. }
  17384. if ( this.array.buffer._uuid === undefined ) {
  17385. this.array.buffer._uuid = generateUUID();
  17386. }
  17387. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17388. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17389. }
  17390. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17391. const ib = new this.constructor( array, this.stride );
  17392. ib.setUsage( this.usage );
  17393. return ib;
  17394. }
  17395. /**
  17396. * Sets the given callback function that is executed after the Renderer has transferred
  17397. * the array data to the GPU. Can be used to perform clean-up operations after
  17398. * the upload when data are not needed anymore on the CPU side.
  17399. *
  17400. * @param {Function} callback - The `onUpload()` callback.
  17401. * @return {InterleavedBuffer} A reference to this instance.
  17402. */
  17403. onUpload( callback ) {
  17404. this.onUploadCallback = callback;
  17405. return this;
  17406. }
  17407. /**
  17408. * Serializes the interleaved buffer into JSON.
  17409. *
  17410. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17411. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17412. */
  17413. toJSON( data ) {
  17414. if ( data.arrayBuffers === undefined ) {
  17415. data.arrayBuffers = {};
  17416. }
  17417. // generate UUID for array buffer if necessary
  17418. if ( this.array.buffer._uuid === undefined ) {
  17419. this.array.buffer._uuid = generateUUID();
  17420. }
  17421. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17422. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17423. }
  17424. //
  17425. return {
  17426. uuid: this.uuid,
  17427. buffer: this.array.buffer._uuid,
  17428. type: this.array.constructor.name,
  17429. stride: this.stride
  17430. };
  17431. }
  17432. }
  17433. const _vector$7 = /*@__PURE__*/ new Vector3();
  17434. /**
  17435. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17436. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17437. * different offsets into the buffer.
  17438. */
  17439. class InterleavedBufferAttribute {
  17440. /**
  17441. * Constructs a new interleaved buffer attribute.
  17442. *
  17443. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17444. * @param {number} itemSize - The item size.
  17445. * @param {number} offset - The attribute offset into the buffer.
  17446. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17447. */
  17448. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17449. /**
  17450. * This flag can be used for type testing.
  17451. *
  17452. * @type {boolean}
  17453. * @readonly
  17454. * @default true
  17455. */
  17456. this.isInterleavedBufferAttribute = true;
  17457. /**
  17458. * The name of the buffer attribute.
  17459. *
  17460. * @type {string}
  17461. */
  17462. this.name = '';
  17463. /**
  17464. * The buffer holding the interleaved data.
  17465. *
  17466. * @type {InterleavedBuffer}
  17467. */
  17468. this.data = interleavedBuffer;
  17469. /**
  17470. * The item size, see {@link BufferAttribute#itemSize}.
  17471. *
  17472. * @type {number}
  17473. */
  17474. this.itemSize = itemSize;
  17475. /**
  17476. * The attribute offset into the buffer.
  17477. *
  17478. * @type {number}
  17479. */
  17480. this.offset = offset;
  17481. /**
  17482. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17483. *
  17484. * @type {InterleavedBuffer}
  17485. */
  17486. this.normalized = normalized;
  17487. }
  17488. /**
  17489. * The item count of this buffer attribute.
  17490. *
  17491. * @type {number}
  17492. * @readonly
  17493. */
  17494. get count() {
  17495. return this.data.count;
  17496. }
  17497. /**
  17498. * The array holding the interleaved buffer attribute data.
  17499. *
  17500. * @type {TypedArray}
  17501. */
  17502. get array() {
  17503. return this.data.array;
  17504. }
  17505. /**
  17506. * Flag to indicate that this attribute has changed and should be re-sent to
  17507. * the GPU. Set this to `true` when you modify the value of the array.
  17508. *
  17509. * @type {number}
  17510. * @default false
  17511. * @param {boolean} value
  17512. */
  17513. set needsUpdate( value ) {
  17514. this.data.needsUpdate = value;
  17515. }
  17516. /**
  17517. * Applies the given 4x4 matrix to the given attribute. Only works with
  17518. * item size `3`.
  17519. *
  17520. * @param {Matrix4} m - The matrix to apply.
  17521. * @return {InterleavedBufferAttribute} A reference to this instance.
  17522. */
  17523. applyMatrix4( m ) {
  17524. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17525. _vector$7.fromBufferAttribute( this, i );
  17526. _vector$7.applyMatrix4( m );
  17527. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17528. }
  17529. return this;
  17530. }
  17531. /**
  17532. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17533. * item size `3`.
  17534. *
  17535. * @param {Matrix3} m - The normal matrix to apply.
  17536. * @return {InterleavedBufferAttribute} A reference to this instance.
  17537. */
  17538. applyNormalMatrix( m ) {
  17539. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17540. _vector$7.fromBufferAttribute( this, i );
  17541. _vector$7.applyNormalMatrix( m );
  17542. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17543. }
  17544. return this;
  17545. }
  17546. /**
  17547. * Applies the given 4x4 matrix to the given attribute. Only works with
  17548. * item size `3` and with direction vectors.
  17549. *
  17550. * @param {Matrix4} m - The matrix to apply.
  17551. * @return {InterleavedBufferAttribute} A reference to this instance.
  17552. */
  17553. transformDirection( m ) {
  17554. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17555. _vector$7.fromBufferAttribute( this, i );
  17556. _vector$7.transformDirection( m );
  17557. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17558. }
  17559. return this;
  17560. }
  17561. /**
  17562. * Returns the given component of the vector at the given index.
  17563. *
  17564. * @param {number} index - The index into the buffer attribute.
  17565. * @param {number} component - The component index.
  17566. * @return {number} The returned value.
  17567. */
  17568. getComponent( index, component ) {
  17569. let value = this.array[ index * this.data.stride + this.offset + component ];
  17570. if ( this.normalized ) value = denormalize( value, this.array );
  17571. return value;
  17572. }
  17573. /**
  17574. * Sets the given value to the given component of the vector at the given index.
  17575. *
  17576. * @param {number} index - The index into the buffer attribute.
  17577. * @param {number} component - The component index.
  17578. * @param {number} value - The value to set.
  17579. * @return {InterleavedBufferAttribute} A reference to this instance.
  17580. */
  17581. setComponent( index, component, value ) {
  17582. if ( this.normalized ) value = normalize( value, this.array );
  17583. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17584. return this;
  17585. }
  17586. /**
  17587. * Sets the x component of the vector at the given index.
  17588. *
  17589. * @param {number} index - The index into the buffer attribute.
  17590. * @param {number} x - The value to set.
  17591. * @return {InterleavedBufferAttribute} A reference to this instance.
  17592. */
  17593. setX( index, x ) {
  17594. if ( this.normalized ) x = normalize( x, this.array );
  17595. this.data.array[ index * this.data.stride + this.offset ] = x;
  17596. return this;
  17597. }
  17598. /**
  17599. * Sets the y component of the vector at the given index.
  17600. *
  17601. * @param {number} index - The index into the buffer attribute.
  17602. * @param {number} y - The value to set.
  17603. * @return {InterleavedBufferAttribute} A reference to this instance.
  17604. */
  17605. setY( index, y ) {
  17606. if ( this.normalized ) y = normalize( y, this.array );
  17607. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17608. return this;
  17609. }
  17610. /**
  17611. * Sets the z component of the vector at the given index.
  17612. *
  17613. * @param {number} index - The index into the buffer attribute.
  17614. * @param {number} z - The value to set.
  17615. * @return {InterleavedBufferAttribute} A reference to this instance.
  17616. */
  17617. setZ( index, z ) {
  17618. if ( this.normalized ) z = normalize( z, this.array );
  17619. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17620. return this;
  17621. }
  17622. /**
  17623. * Sets the w component of the vector at the given index.
  17624. *
  17625. * @param {number} index - The index into the buffer attribute.
  17626. * @param {number} w - The value to set.
  17627. * @return {InterleavedBufferAttribute} A reference to this instance.
  17628. */
  17629. setW( index, w ) {
  17630. if ( this.normalized ) w = normalize( w, this.array );
  17631. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17632. return this;
  17633. }
  17634. /**
  17635. * Returns the x component of the vector at the given index.
  17636. *
  17637. * @param {number} index - The index into the buffer attribute.
  17638. * @return {number} The x component.
  17639. */
  17640. getX( index ) {
  17641. let x = this.data.array[ index * this.data.stride + this.offset ];
  17642. if ( this.normalized ) x = denormalize( x, this.array );
  17643. return x;
  17644. }
  17645. /**
  17646. * Returns the y component of the vector at the given index.
  17647. *
  17648. * @param {number} index - The index into the buffer attribute.
  17649. * @return {number} The y component.
  17650. */
  17651. getY( index ) {
  17652. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17653. if ( this.normalized ) y = denormalize( y, this.array );
  17654. return y;
  17655. }
  17656. /**
  17657. * Returns the z component of the vector at the given index.
  17658. *
  17659. * @param {number} index - The index into the buffer attribute.
  17660. * @return {number} The z component.
  17661. */
  17662. getZ( index ) {
  17663. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17664. if ( this.normalized ) z = denormalize( z, this.array );
  17665. return z;
  17666. }
  17667. /**
  17668. * Returns the w component of the vector at the given index.
  17669. *
  17670. * @param {number} index - The index into the buffer attribute.
  17671. * @return {number} The w component.
  17672. */
  17673. getW( index ) {
  17674. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17675. if ( this.normalized ) w = denormalize( w, this.array );
  17676. return w;
  17677. }
  17678. /**
  17679. * Sets the x and y component of the vector at the given index.
  17680. *
  17681. * @param {number} index - The index into the buffer attribute.
  17682. * @param {number} x - The value for the x component to set.
  17683. * @param {number} y - The value for the y component to set.
  17684. * @return {InterleavedBufferAttribute} A reference to this instance.
  17685. */
  17686. setXY( index, x, y ) {
  17687. index = index * this.data.stride + this.offset;
  17688. if ( this.normalized ) {
  17689. x = normalize( x, this.array );
  17690. y = normalize( y, this.array );
  17691. }
  17692. this.data.array[ index + 0 ] = x;
  17693. this.data.array[ index + 1 ] = y;
  17694. return this;
  17695. }
  17696. /**
  17697. * Sets the x, y and z component of the vector at the given index.
  17698. *
  17699. * @param {number} index - The index into the buffer attribute.
  17700. * @param {number} x - The value for the x component to set.
  17701. * @param {number} y - The value for the y component to set.
  17702. * @param {number} z - The value for the z component to set.
  17703. * @return {InterleavedBufferAttribute} A reference to this instance.
  17704. */
  17705. setXYZ( index, x, y, z ) {
  17706. index = index * this.data.stride + this.offset;
  17707. if ( this.normalized ) {
  17708. x = normalize( x, this.array );
  17709. y = normalize( y, this.array );
  17710. z = normalize( z, this.array );
  17711. }
  17712. this.data.array[ index + 0 ] = x;
  17713. this.data.array[ index + 1 ] = y;
  17714. this.data.array[ index + 2 ] = z;
  17715. return this;
  17716. }
  17717. /**
  17718. * Sets the x, y, z and w component of the vector at the given index.
  17719. *
  17720. * @param {number} index - The index into the buffer attribute.
  17721. * @param {number} x - The value for the x component to set.
  17722. * @param {number} y - The value for the y component to set.
  17723. * @param {number} z - The value for the z component to set.
  17724. * @param {number} w - The value for the w component to set.
  17725. * @return {InterleavedBufferAttribute} A reference to this instance.
  17726. */
  17727. setXYZW( index, x, y, z, w ) {
  17728. index = index * this.data.stride + this.offset;
  17729. if ( this.normalized ) {
  17730. x = normalize( x, this.array );
  17731. y = normalize( y, this.array );
  17732. z = normalize( z, this.array );
  17733. w = normalize( w, this.array );
  17734. }
  17735. this.data.array[ index + 0 ] = x;
  17736. this.data.array[ index + 1 ] = y;
  17737. this.data.array[ index + 2 ] = z;
  17738. this.data.array[ index + 3 ] = w;
  17739. return this;
  17740. }
  17741. /**
  17742. * Returns a new buffer attribute with copied values from this instance.
  17743. *
  17744. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17745. *
  17746. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17747. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17748. */
  17749. clone( data ) {
  17750. if ( data === undefined ) {
  17751. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17752. const array = [];
  17753. for ( let i = 0; i < this.count; i ++ ) {
  17754. const index = i * this.data.stride + this.offset;
  17755. for ( let j = 0; j < this.itemSize; j ++ ) {
  17756. array.push( this.data.array[ index + j ] );
  17757. }
  17758. }
  17759. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17760. } else {
  17761. if ( data.interleavedBuffers === undefined ) {
  17762. data.interleavedBuffers = {};
  17763. }
  17764. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17765. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17766. }
  17767. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17768. }
  17769. }
  17770. /**
  17771. * Serializes the buffer attribute into JSON.
  17772. *
  17773. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17774. *
  17775. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17776. * @return {Object} A JSON object representing the serialized buffer attribute.
  17777. */
  17778. toJSON( data ) {
  17779. if ( data === undefined ) {
  17780. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17781. const array = [];
  17782. for ( let i = 0; i < this.count; i ++ ) {
  17783. const index = i * this.data.stride + this.offset;
  17784. for ( let j = 0; j < this.itemSize; j ++ ) {
  17785. array.push( this.data.array[ index + j ] );
  17786. }
  17787. }
  17788. // de-interleave data and save it as an ordinary buffer attribute for now
  17789. return {
  17790. itemSize: this.itemSize,
  17791. type: this.array.constructor.name,
  17792. array: array,
  17793. normalized: this.normalized
  17794. };
  17795. } else {
  17796. // save as true interleaved attribute
  17797. if ( data.interleavedBuffers === undefined ) {
  17798. data.interleavedBuffers = {};
  17799. }
  17800. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17801. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17802. }
  17803. return {
  17804. isInterleavedBufferAttribute: true,
  17805. itemSize: this.itemSize,
  17806. data: this.data.uuid,
  17807. offset: this.offset,
  17808. normalized: this.normalized
  17809. };
  17810. }
  17811. }
  17812. }
  17813. /**
  17814. * A material for rendering instances of {@link Sprite}.
  17815. *
  17816. * ```js
  17817. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17818. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17819. *
  17820. * const sprite = new THREE.Sprite( material );
  17821. * sprite.scale.set(200, 200, 1)
  17822. * scene.add( sprite );
  17823. * ```
  17824. *
  17825. * @augments Material
  17826. */
  17827. class SpriteMaterial extends Material {
  17828. /**
  17829. * Constructs a new sprite material.
  17830. *
  17831. * @param {Object} [parameters] - An object with one or more properties
  17832. * defining the material's appearance. Any property of the material
  17833. * (including any property from inherited materials) can be passed
  17834. * in here. Color values can be passed any type of value accepted
  17835. * by {@link Color#set}.
  17836. */
  17837. constructor( parameters ) {
  17838. super();
  17839. /**
  17840. * This flag can be used for type testing.
  17841. *
  17842. * @type {boolean}
  17843. * @readonly
  17844. * @default true
  17845. */
  17846. this.isSpriteMaterial = true;
  17847. this.type = 'SpriteMaterial';
  17848. /**
  17849. * Color of the material.
  17850. *
  17851. * @type {Color}
  17852. * @default (1,1,1)
  17853. */
  17854. this.color = new Color( 0xffffff );
  17855. /**
  17856. * The color map. May optionally include an alpha channel, typically combined
  17857. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17858. * color is modulated by the diffuse `color`.
  17859. *
  17860. * @type {?Texture}
  17861. * @default null
  17862. */
  17863. this.map = null;
  17864. /**
  17865. * The alpha map is a grayscale texture that controls the opacity across the
  17866. * surface (black: fully transparent; white: fully opaque).
  17867. *
  17868. * Only the color of the texture is used, ignoring the alpha channel if one
  17869. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17870. * when sampling this texture due to the extra bit of precision provided for
  17871. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17872. * luminance/alpha textures will also still work as expected.
  17873. *
  17874. * @type {?Texture}
  17875. * @default null
  17876. */
  17877. this.alphaMap = null;
  17878. /**
  17879. * The rotation of the sprite in radians.
  17880. *
  17881. * @type {number}
  17882. * @default 0
  17883. */
  17884. this.rotation = 0;
  17885. /**
  17886. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  17887. *
  17888. * @type {boolean}
  17889. * @default true
  17890. */
  17891. this.sizeAttenuation = true;
  17892. /**
  17893. * Overwritten since sprite materials are transparent
  17894. * by default.
  17895. *
  17896. * @type {boolean}
  17897. * @default true
  17898. */
  17899. this.transparent = true;
  17900. /**
  17901. * Whether the material is affected by fog or not.
  17902. *
  17903. * @type {boolean}
  17904. * @default true
  17905. */
  17906. this.fog = true;
  17907. this.setValues( parameters );
  17908. }
  17909. copy( source ) {
  17910. super.copy( source );
  17911. this.color.copy( source.color );
  17912. this.map = source.map;
  17913. this.alphaMap = source.alphaMap;
  17914. this.rotation = source.rotation;
  17915. this.sizeAttenuation = source.sizeAttenuation;
  17916. this.fog = source.fog;
  17917. return this;
  17918. }
  17919. }
  17920. let _geometry;
  17921. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17922. const _worldScale = /*@__PURE__*/ new Vector3();
  17923. const _mvPosition = /*@__PURE__*/ new Vector3();
  17924. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17925. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17926. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17927. const _vA = /*@__PURE__*/ new Vector3();
  17928. const _vB = /*@__PURE__*/ new Vector3();
  17929. const _vC = /*@__PURE__*/ new Vector3();
  17930. const _uvA = /*@__PURE__*/ new Vector2();
  17931. const _uvB = /*@__PURE__*/ new Vector2();
  17932. const _uvC = /*@__PURE__*/ new Vector2();
  17933. /**
  17934. * A sprite is a plane that always faces towards the camera, generally with a
  17935. * partially transparent texture applied.
  17936. *
  17937. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  17938. * have no effect.
  17939. *
  17940. * ```js
  17941. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  17942. * const material = new THREE.SpriteMaterial( { map: map } );
  17943. *
  17944. * const sprite = new THREE.Sprite( material );
  17945. * scene.add( sprite );
  17946. * ```
  17947. *
  17948. * @augments Object3D
  17949. */
  17950. class Sprite extends Object3D {
  17951. /**
  17952. * Constructs a new sprite.
  17953. *
  17954. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  17955. */
  17956. constructor( material = new SpriteMaterial() ) {
  17957. super();
  17958. /**
  17959. * This flag can be used for type testing.
  17960. *
  17961. * @type {boolean}
  17962. * @readonly
  17963. * @default true
  17964. */
  17965. this.isSprite = true;
  17966. this.type = 'Sprite';
  17967. if ( _geometry === undefined ) {
  17968. _geometry = new BufferGeometry();
  17969. const float32Array = new Float32Array( [
  17970. -0.5, -0.5, 0, 0, 0,
  17971. 0.5, -0.5, 0, 1, 0,
  17972. 0.5, 0.5, 0, 1, 1,
  17973. -0.5, 0.5, 0, 0, 1
  17974. ] );
  17975. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17976. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17977. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17978. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17979. }
  17980. /**
  17981. * The sprite geometry.
  17982. *
  17983. * @type {BufferGeometry}
  17984. */
  17985. this.geometry = _geometry;
  17986. /**
  17987. * The sprite material.
  17988. *
  17989. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  17990. */
  17991. this.material = material;
  17992. /**
  17993. * The sprite's anchor point, and the point around which the sprite rotates.
  17994. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  17995. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  17996. *
  17997. * @type {Vector2}
  17998. * @default (0.5,0.5)
  17999. */
  18000. this.center = new Vector2( 0.5, 0.5 );
  18001. /**
  18002. * The number of instances of this sprite.
  18003. * Can only be used with {@link WebGPURenderer}.
  18004. *
  18005. * @type {number}
  18006. * @default 1
  18007. */
  18008. this.count = 1;
  18009. }
  18010. /**
  18011. * Computes intersection points between a casted ray and this sprite.
  18012. *
  18013. * @param {Raycaster} raycaster - The raycaster.
  18014. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18015. */
  18016. raycast( raycaster, intersects ) {
  18017. if ( raycaster.camera === null ) {
  18018. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18019. }
  18020. _worldScale.setFromMatrixScale( this.matrixWorld );
  18021. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18022. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18023. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18024. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18025. _worldScale.multiplyScalar( - _mvPosition.z );
  18026. }
  18027. const rotation = this.material.rotation;
  18028. let sin, cos;
  18029. if ( rotation !== 0 ) {
  18030. cos = Math.cos( rotation );
  18031. sin = Math.sin( rotation );
  18032. }
  18033. const center = this.center;
  18034. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18035. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18036. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18037. _uvA.set( 0, 0 );
  18038. _uvB.set( 1, 0 );
  18039. _uvC.set( 1, 1 );
  18040. // check first triangle
  18041. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18042. if ( intersect === null ) {
  18043. // check second triangle
  18044. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18045. _uvB.set( 0, 1 );
  18046. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18047. if ( intersect === null ) {
  18048. return;
  18049. }
  18050. }
  18051. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18052. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18053. intersects.push( {
  18054. distance: distance,
  18055. point: _intersectPoint.clone(),
  18056. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18057. face: null,
  18058. object: this
  18059. } );
  18060. }
  18061. copy( source, recursive ) {
  18062. super.copy( source, recursive );
  18063. if ( source.center !== undefined ) this.center.copy( source.center );
  18064. this.material = source.material;
  18065. return this;
  18066. }
  18067. }
  18068. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18069. // compute position in camera space
  18070. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18071. // to check if rotation is not zero
  18072. if ( sin !== undefined ) {
  18073. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18074. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18075. } else {
  18076. _rotatedPosition.copy( _alignedPosition );
  18077. }
  18078. vertexPosition.copy( mvPosition );
  18079. vertexPosition.x += _rotatedPosition.x;
  18080. vertexPosition.y += _rotatedPosition.y;
  18081. // transform to world space
  18082. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18083. }
  18084. const _v1$2 = /*@__PURE__*/ new Vector3();
  18085. const _v2$1 = /*@__PURE__*/ new Vector3();
  18086. /**
  18087. * A component for providing a basic Level of Detail (LOD) mechanism.
  18088. *
  18089. * Every LOD level is associated with an object, and rendering can be switched
  18090. * between them at the distances specified. Typically you would create, say,
  18091. * three meshes, one for far away (low detail), one for mid range (medium
  18092. * detail) and one for close up (high detail).
  18093. *
  18094. * ```js
  18095. * const lod = new THREE.LOD();
  18096. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18097. *
  18098. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18099. * for( let i = 0; i < 3; i++ ) {
  18100. *
  18101. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18102. * const mesh = new THREE.Mesh( geometry, material );
  18103. * lod.addLevel( mesh, i * 75 );
  18104. *
  18105. * }
  18106. *
  18107. * scene.add( lod );
  18108. * ```
  18109. *
  18110. * @augments Object3D
  18111. */
  18112. class LOD extends Object3D {
  18113. /**
  18114. * Constructs a new LOD.
  18115. */
  18116. constructor() {
  18117. super();
  18118. /**
  18119. * This flag can be used for type testing.
  18120. *
  18121. * @type {boolean}
  18122. * @readonly
  18123. * @default true
  18124. */
  18125. this.isLOD = true;
  18126. /**
  18127. * The current LOD index.
  18128. *
  18129. * @private
  18130. * @type {number}
  18131. * @default 0
  18132. */
  18133. this._currentLevel = 0;
  18134. this.type = 'LOD';
  18135. Object.defineProperties( this, {
  18136. /**
  18137. * This array holds the LOD levels.
  18138. *
  18139. * @name LOD#levels
  18140. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18141. */
  18142. levels: {
  18143. enumerable: true,
  18144. value: []
  18145. }
  18146. } );
  18147. /**
  18148. * Whether the LOD object is updated automatically by the renderer per frame
  18149. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18150. * render loop by yourself.
  18151. *
  18152. * @type {boolean}
  18153. * @default true
  18154. */
  18155. this.autoUpdate = true;
  18156. }
  18157. copy( source ) {
  18158. super.copy( source, false );
  18159. const levels = source.levels;
  18160. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18161. const level = levels[ i ];
  18162. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18163. }
  18164. this.autoUpdate = source.autoUpdate;
  18165. return this;
  18166. }
  18167. /**
  18168. * Adds a mesh that will display at a certain distance and greater. Typically
  18169. * the further away the distance, the lower the detail on the mesh.
  18170. *
  18171. * @param {Object3D} object - The 3D object to display at this level.
  18172. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18173. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18174. * @return {LOD} A reference to this instance.
  18175. */
  18176. addLevel( object, distance = 0, hysteresis = 0 ) {
  18177. distance = Math.abs( distance );
  18178. const levels = this.levels;
  18179. let l;
  18180. for ( l = 0; l < levels.length; l ++ ) {
  18181. if ( distance < levels[ l ].distance ) {
  18182. break;
  18183. }
  18184. }
  18185. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18186. this.add( object );
  18187. return this;
  18188. }
  18189. /**
  18190. * Removes an existing level, based on the distance from the camera.
  18191. * Returns `true` when the level has been removed. Otherwise `false`.
  18192. *
  18193. * @param {number} distance - Distance of the level to remove.
  18194. * @return {boolean} Whether the level has been removed or not.
  18195. */
  18196. removeLevel( distance ) {
  18197. const levels = this.levels;
  18198. for ( let i = 0; i < levels.length; i ++ ) {
  18199. if ( levels[ i ].distance === distance ) {
  18200. const removedElements = levels.splice( i, 1 );
  18201. this.remove( removedElements[ 0 ].object );
  18202. return true;
  18203. }
  18204. }
  18205. return false;
  18206. }
  18207. /**
  18208. * Returns the currently active LOD level index.
  18209. *
  18210. * @return {number} The current active LOD level index.
  18211. */
  18212. getCurrentLevel() {
  18213. return this._currentLevel;
  18214. }
  18215. /**
  18216. * Returns a reference to the first 3D object that is greater than
  18217. * the given distance.
  18218. *
  18219. * @param {number} distance - The LOD distance.
  18220. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  18221. */
  18222. getObjectForDistance( distance ) {
  18223. const levels = this.levels;
  18224. if ( levels.length > 0 ) {
  18225. let i, l;
  18226. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18227. let levelDistance = levels[ i ].distance;
  18228. if ( levels[ i ].object.visible ) {
  18229. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18230. }
  18231. if ( distance < levelDistance ) {
  18232. break;
  18233. }
  18234. }
  18235. return levels[ i - 1 ].object;
  18236. }
  18237. return null;
  18238. }
  18239. /**
  18240. * Computes intersection points between a casted ray and this LOD.
  18241. *
  18242. * @param {Raycaster} raycaster - The raycaster.
  18243. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18244. */
  18245. raycast( raycaster, intersects ) {
  18246. const levels = this.levels;
  18247. if ( levels.length > 0 ) {
  18248. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18249. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18250. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18251. }
  18252. }
  18253. /**
  18254. * Updates the LOD by computing which LOD level should be visible according
  18255. * to the current distance of the given camera.
  18256. *
  18257. * @param {Camera} camera - The camera the scene is rendered with.
  18258. */
  18259. update( camera ) {
  18260. const levels = this.levels;
  18261. if ( levels.length > 1 ) {
  18262. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18263. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18264. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18265. levels[ 0 ].object.visible = true;
  18266. let i, l;
  18267. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18268. let levelDistance = levels[ i ].distance;
  18269. if ( levels[ i ].object.visible ) {
  18270. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18271. }
  18272. if ( distance >= levelDistance ) {
  18273. levels[ i - 1 ].object.visible = false;
  18274. levels[ i ].object.visible = true;
  18275. } else {
  18276. break;
  18277. }
  18278. }
  18279. this._currentLevel = i - 1;
  18280. for ( ; i < l; i ++ ) {
  18281. levels[ i ].object.visible = false;
  18282. }
  18283. }
  18284. }
  18285. toJSON( meta ) {
  18286. const data = super.toJSON( meta );
  18287. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18288. data.object.levels = [];
  18289. const levels = this.levels;
  18290. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18291. const level = levels[ i ];
  18292. data.object.levels.push( {
  18293. object: level.object.uuid,
  18294. distance: level.distance,
  18295. hysteresis: level.hysteresis
  18296. } );
  18297. }
  18298. return data;
  18299. }
  18300. }
  18301. const _basePosition = /*@__PURE__*/ new Vector3();
  18302. const _skinIndex = /*@__PURE__*/ new Vector4();
  18303. const _skinWeight = /*@__PURE__*/ new Vector4();
  18304. const _vector3 = /*@__PURE__*/ new Vector3();
  18305. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18306. const _vertex = /*@__PURE__*/ new Vector3();
  18307. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18308. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18309. const _ray$2 = /*@__PURE__*/ new Ray();
  18310. /**
  18311. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18312. * vertices of the geometry with skinning/skeleton animation.
  18313. *
  18314. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18315. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18316. * vertex to a certain extend.
  18317. *
  18318. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18319. * or {@link FBXLoader } import respective models.
  18320. *
  18321. * @augments Mesh
  18322. */
  18323. class SkinnedMesh extends Mesh {
  18324. /**
  18325. * Constructs a new skinned mesh.
  18326. *
  18327. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18328. * @param {Material|Array<Material>} [material] - The mesh material.
  18329. */
  18330. constructor( geometry, material ) {
  18331. super( geometry, material );
  18332. /**
  18333. * This flag can be used for type testing.
  18334. *
  18335. * @type {boolean}
  18336. * @readonly
  18337. * @default true
  18338. */
  18339. this.isSkinnedMesh = true;
  18340. this.type = 'SkinnedMesh';
  18341. /**
  18342. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18343. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18344. * across multiple skinned meshes.
  18345. *
  18346. * @type {(AttachedBindMode|DetachedBindMode)}
  18347. * @default AttachedBindMode
  18348. */
  18349. this.bindMode = AttachedBindMode;
  18350. /**
  18351. * The base matrix that is used for the bound bone transforms.
  18352. *
  18353. * @type {Matrix4}
  18354. */
  18355. this.bindMatrix = new Matrix4();
  18356. /**
  18357. * The base matrix that is used for resetting the bound bone transforms.
  18358. *
  18359. * @type {Matrix4}
  18360. */
  18361. this.bindMatrixInverse = new Matrix4();
  18362. /**
  18363. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18364. *
  18365. * @type {?Box3}
  18366. * @default null
  18367. */
  18368. this.boundingBox = null;
  18369. /**
  18370. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18371. *
  18372. * @type {?Sphere}
  18373. * @default null
  18374. */
  18375. this.boundingSphere = null;
  18376. }
  18377. /**
  18378. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18379. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18380. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18381. * the current animation state.
  18382. */
  18383. computeBoundingBox() {
  18384. const geometry = this.geometry;
  18385. if ( this.boundingBox === null ) {
  18386. this.boundingBox = new Box3();
  18387. }
  18388. this.boundingBox.makeEmpty();
  18389. const positionAttribute = geometry.getAttribute( 'position' );
  18390. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18391. this.getVertexPosition( i, _vertex );
  18392. this.boundingBox.expandByPoint( _vertex );
  18393. }
  18394. }
  18395. /**
  18396. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18397. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18398. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18399. * per frame in order to reflect the current animation state.
  18400. */
  18401. computeBoundingSphere() {
  18402. const geometry = this.geometry;
  18403. if ( this.boundingSphere === null ) {
  18404. this.boundingSphere = new Sphere();
  18405. }
  18406. this.boundingSphere.makeEmpty();
  18407. const positionAttribute = geometry.getAttribute( 'position' );
  18408. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18409. this.getVertexPosition( i, _vertex );
  18410. this.boundingSphere.expandByPoint( _vertex );
  18411. }
  18412. }
  18413. copy( source, recursive ) {
  18414. super.copy( source, recursive );
  18415. this.bindMode = source.bindMode;
  18416. this.bindMatrix.copy( source.bindMatrix );
  18417. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18418. this.skeleton = source.skeleton;
  18419. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18420. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18421. return this;
  18422. }
  18423. raycast( raycaster, intersects ) {
  18424. const material = this.material;
  18425. const matrixWorld = this.matrixWorld;
  18426. if ( material === undefined ) return;
  18427. // test with bounding sphere in world space
  18428. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18429. _sphere$5.copy( this.boundingSphere );
  18430. _sphere$5.applyMatrix4( matrixWorld );
  18431. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18432. // convert ray to local space of skinned mesh
  18433. _inverseMatrix$2.copy( matrixWorld ).invert();
  18434. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18435. // test with bounding box in local space
  18436. if ( this.boundingBox !== null ) {
  18437. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18438. }
  18439. // test for intersections with geometry
  18440. this._computeIntersections( raycaster, intersects, _ray$2 );
  18441. }
  18442. getVertexPosition( index, target ) {
  18443. super.getVertexPosition( index, target );
  18444. this.applyBoneTransform( index, target );
  18445. return target;
  18446. }
  18447. /**
  18448. * Binds the given skeleton to the skinned mesh.
  18449. *
  18450. * @param {Skeleton} skeleton - The skeleton to bind.
  18451. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18452. * the skinned mesh's world matrix will be used instead.
  18453. */
  18454. bind( skeleton, bindMatrix ) {
  18455. this.skeleton = skeleton;
  18456. if ( bindMatrix === undefined ) {
  18457. this.updateMatrixWorld( true );
  18458. this.skeleton.calculateInverses();
  18459. bindMatrix = this.matrixWorld;
  18460. }
  18461. this.bindMatrix.copy( bindMatrix );
  18462. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18463. }
  18464. /**
  18465. * This method sets the skinned mesh in the rest pose).
  18466. */
  18467. pose() {
  18468. this.skeleton.pose();
  18469. }
  18470. /**
  18471. * Normalizes the skin weights which are defined as a buffer attribute
  18472. * in the skinned mesh's geometry.
  18473. */
  18474. normalizeSkinWeights() {
  18475. const vector = new Vector4();
  18476. const skinWeight = this.geometry.attributes.skinWeight;
  18477. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18478. vector.fromBufferAttribute( skinWeight, i );
  18479. const scale = 1.0 / vector.manhattanLength();
  18480. if ( scale !== Infinity ) {
  18481. vector.multiplyScalar( scale );
  18482. } else {
  18483. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18484. }
  18485. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18486. }
  18487. }
  18488. updateMatrixWorld( force ) {
  18489. super.updateMatrixWorld( force );
  18490. if ( this.bindMode === AttachedBindMode ) {
  18491. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18492. } else if ( this.bindMode === DetachedBindMode ) {
  18493. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18494. } else {
  18495. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18496. }
  18497. }
  18498. /**
  18499. * Applies the bone transform associated with the given index to the given
  18500. * vertex position. Returns the updated vector.
  18501. *
  18502. * @param {number} index - The vertex index.
  18503. * @param {Vector3} target - The target object that is used to store the method's result.
  18504. * the skinned mesh's world matrix will be used instead.
  18505. * @return {Vector3} The updated vertex position.
  18506. */
  18507. applyBoneTransform( index, target ) {
  18508. const skeleton = this.skeleton;
  18509. const geometry = this.geometry;
  18510. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18511. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18512. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18513. target.set( 0, 0, 0 );
  18514. for ( let i = 0; i < 4; i ++ ) {
  18515. const weight = _skinWeight.getComponent( i );
  18516. if ( weight !== 0 ) {
  18517. const boneIndex = _skinIndex.getComponent( i );
  18518. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18519. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18520. }
  18521. }
  18522. return target.applyMatrix4( this.bindMatrixInverse );
  18523. }
  18524. }
  18525. /**
  18526. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18527. * the {@link SkinnedMesh}.
  18528. *
  18529. * ```js
  18530. * const root = new THREE.Bone();
  18531. * const child = new THREE.Bone();
  18532. *
  18533. * root.add( child );
  18534. * child.position.y = 5;
  18535. * ```
  18536. *
  18537. * @augments Object3D
  18538. */
  18539. class Bone extends Object3D {
  18540. /**
  18541. * Constructs a new bone.
  18542. */
  18543. constructor() {
  18544. super();
  18545. /**
  18546. * This flag can be used for type testing.
  18547. *
  18548. * @type {boolean}
  18549. * @readonly
  18550. * @default true
  18551. */
  18552. this.isBone = true;
  18553. this.type = 'Bone';
  18554. }
  18555. }
  18556. /**
  18557. * Creates a texture directly from raw buffer data.
  18558. *
  18559. * The interpretation of the data depends on type and format: If the type is
  18560. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18561. * texel data. If the format is `RGBAFormat`, data needs four values for
  18562. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18563. *
  18564. * @augments Texture
  18565. */
  18566. class DataTexture extends Texture {
  18567. /**
  18568. * Constructs a new data texture.
  18569. *
  18570. * @param {?TypedArray} [data=null] - The buffer data.
  18571. * @param {number} [width=1] - The width of the texture.
  18572. * @param {number} [height=1] - The height of the texture.
  18573. * @param {number} [format=RGBAFormat] - The texture format.
  18574. * @param {number} [type=UnsignedByteType] - The texture type.
  18575. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18576. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18577. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18578. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18579. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18580. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18581. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18582. */
  18583. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18584. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18585. /**
  18586. * This flag can be used for type testing.
  18587. *
  18588. * @type {boolean}
  18589. * @readonly
  18590. * @default true
  18591. */
  18592. this.isDataTexture = true;
  18593. /**
  18594. * The image definition of a data texture.
  18595. *
  18596. * @type {{data:TypedArray,width:number,height:number}}
  18597. */
  18598. this.image = { data: data, width: width, height: height };
  18599. /**
  18600. * Whether to generate mipmaps (if possible) for a texture.
  18601. *
  18602. * Overwritten and set to `false` by default.
  18603. *
  18604. * @type {boolean}
  18605. * @default false
  18606. */
  18607. this.generateMipmaps = false;
  18608. /**
  18609. * If set to `true`, the texture is flipped along the vertical axis when
  18610. * uploaded to the GPU.
  18611. *
  18612. * Overwritten and set to `false` by default.
  18613. *
  18614. * @type {boolean}
  18615. * @default false
  18616. */
  18617. this.flipY = false;
  18618. /**
  18619. * Specifies the alignment requirements for the start of each pixel row in memory.
  18620. *
  18621. * Overwritten and set to `1` by default.
  18622. *
  18623. * @type {boolean}
  18624. * @default 1
  18625. */
  18626. this.unpackAlignment = 1;
  18627. }
  18628. }
  18629. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18630. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18631. /**
  18632. * Class for representing the armatures in `three.js`. The skeleton
  18633. * is defined by a hierarchy of bones.
  18634. *
  18635. * ```js
  18636. * const bones = [];
  18637. *
  18638. * const shoulder = new THREE.Bone();
  18639. * const elbow = new THREE.Bone();
  18640. * const hand = new THREE.Bone();
  18641. *
  18642. * shoulder.add( elbow );
  18643. * elbow.add( hand );
  18644. *
  18645. * bones.push( shoulder , elbow, hand);
  18646. *
  18647. * shoulder.position.y = -5;
  18648. * elbow.position.y = 0;
  18649. * hand.position.y = 5;
  18650. *
  18651. * const armSkeleton = new THREE.Skeleton( bones );
  18652. * ```
  18653. */
  18654. class Skeleton {
  18655. /**
  18656. * Constructs a new skeleton.
  18657. *
  18658. * @param {Array<Bone>} [bones] - An array of bones.
  18659. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18660. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18661. */
  18662. constructor( bones = [], boneInverses = [] ) {
  18663. this.uuid = generateUUID();
  18664. /**
  18665. * An array of bones defining the skeleton.
  18666. *
  18667. * @type {Array<Bone>}
  18668. */
  18669. this.bones = bones.slice( 0 );
  18670. /**
  18671. * An array of bone inverse matrices.
  18672. *
  18673. * @type {Array<Matrix4>}
  18674. */
  18675. this.boneInverses = boneInverses;
  18676. /**
  18677. * An array buffer holding the bone data.
  18678. * Input data for {@link Skeleton#boneTexture}.
  18679. *
  18680. * @type {?Float32Array}
  18681. * @default null
  18682. */
  18683. this.boneMatrices = null;
  18684. /**
  18685. * A texture holding the bone data for use
  18686. * in the vertex shader.
  18687. *
  18688. * @type {?DataTexture}
  18689. * @default null
  18690. */
  18691. this.boneTexture = null;
  18692. this.init();
  18693. }
  18694. /**
  18695. * Initializes the skeleton. This method gets automatically called by the constructor
  18696. * but depending on how the skeleton is created it might be necessary to call this method
  18697. * manually.
  18698. */
  18699. init() {
  18700. const bones = this.bones;
  18701. const boneInverses = this.boneInverses;
  18702. this.boneMatrices = new Float32Array( bones.length * 16 );
  18703. // calculate inverse bone matrices if necessary
  18704. if ( boneInverses.length === 0 ) {
  18705. this.calculateInverses();
  18706. } else {
  18707. // handle special case
  18708. if ( bones.length !== boneInverses.length ) {
  18709. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18710. this.boneInverses = [];
  18711. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18712. this.boneInverses.push( new Matrix4() );
  18713. }
  18714. }
  18715. }
  18716. }
  18717. /**
  18718. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18719. * and fills it with new matrices.
  18720. */
  18721. calculateInverses() {
  18722. this.boneInverses.length = 0;
  18723. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18724. const inverse = new Matrix4();
  18725. if ( this.bones[ i ] ) {
  18726. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18727. }
  18728. this.boneInverses.push( inverse );
  18729. }
  18730. }
  18731. /**
  18732. * Resets the skeleton to the base pose.
  18733. */
  18734. pose() {
  18735. // recover the bind-time world matrices
  18736. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18737. const bone = this.bones[ i ];
  18738. if ( bone ) {
  18739. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18740. }
  18741. }
  18742. // compute the local matrices, positions, rotations and scales
  18743. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18744. const bone = this.bones[ i ];
  18745. if ( bone ) {
  18746. if ( bone.parent && bone.parent.isBone ) {
  18747. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18748. bone.matrix.multiply( bone.matrixWorld );
  18749. } else {
  18750. bone.matrix.copy( bone.matrixWorld );
  18751. }
  18752. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18753. }
  18754. }
  18755. }
  18756. /**
  18757. * Resets the skeleton to the base pose.
  18758. */
  18759. update() {
  18760. const bones = this.bones;
  18761. const boneInverses = this.boneInverses;
  18762. const boneMatrices = this.boneMatrices;
  18763. const boneTexture = this.boneTexture;
  18764. // flatten bone matrices to array
  18765. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18766. // compute the offset between the current and the original transform
  18767. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18768. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18769. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18770. }
  18771. if ( boneTexture !== null ) {
  18772. boneTexture.needsUpdate = true;
  18773. }
  18774. }
  18775. /**
  18776. * Returns a new skeleton with copied values from this instance.
  18777. *
  18778. * @return {Skeleton} A clone of this instance.
  18779. */
  18780. clone() {
  18781. return new Skeleton( this.bones, this.boneInverses );
  18782. }
  18783. /**
  18784. * Computes a data texture for passing bone data to the vertex shader.
  18785. *
  18786. * @return {Skeleton} A reference of this instance.
  18787. */
  18788. computeBoneTexture() {
  18789. // layout (1 matrix = 4 pixels)
  18790. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18791. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18792. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18793. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18794. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18795. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18796. size = Math.ceil( size / 4 ) * 4;
  18797. size = Math.max( size, 4 );
  18798. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18799. boneMatrices.set( this.boneMatrices ); // copy current values
  18800. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18801. boneTexture.needsUpdate = true;
  18802. this.boneMatrices = boneMatrices;
  18803. this.boneTexture = boneTexture;
  18804. return this;
  18805. }
  18806. /**
  18807. * Searches through the skeleton's bone array and returns the first with a
  18808. * matching name.
  18809. *
  18810. * @param {string} name - The name of the bone.
  18811. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18812. */
  18813. getBoneByName( name ) {
  18814. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18815. const bone = this.bones[ i ];
  18816. if ( bone.name === name ) {
  18817. return bone;
  18818. }
  18819. }
  18820. return undefined;
  18821. }
  18822. /**
  18823. * Frees the GPU-related resources allocated by this instance. Call this
  18824. * method whenever this instance is no longer used in your app.
  18825. */
  18826. dispose( ) {
  18827. if ( this.boneTexture !== null ) {
  18828. this.boneTexture.dispose();
  18829. this.boneTexture = null;
  18830. }
  18831. }
  18832. /**
  18833. * Setups the skeleton by the given JSON and bones.
  18834. *
  18835. * @param {Object} json - The skeleton as serialized JSON.
  18836. * @param {Object<string, Bone>} bones - An array of bones.
  18837. * @return {Skeleton} A reference of this instance.
  18838. */
  18839. fromJSON( json, bones ) {
  18840. this.uuid = json.uuid;
  18841. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18842. const uuid = json.bones[ i ];
  18843. let bone = bones[ uuid ];
  18844. if ( bone === undefined ) {
  18845. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18846. bone = new Bone();
  18847. }
  18848. this.bones.push( bone );
  18849. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18850. }
  18851. this.init();
  18852. return this;
  18853. }
  18854. /**
  18855. * Serializes the skeleton into JSON.
  18856. *
  18857. * @return {Object} A JSON object representing the serialized skeleton.
  18858. * @see {@link ObjectLoader#parse}
  18859. */
  18860. toJSON() {
  18861. const data = {
  18862. metadata: {
  18863. version: 4.7,
  18864. type: 'Skeleton',
  18865. generator: 'Skeleton.toJSON'
  18866. },
  18867. bones: [],
  18868. boneInverses: []
  18869. };
  18870. data.uuid = this.uuid;
  18871. const bones = this.bones;
  18872. const boneInverses = this.boneInverses;
  18873. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18874. const bone = bones[ i ];
  18875. data.bones.push( bone.uuid );
  18876. const boneInverse = boneInverses[ i ];
  18877. data.boneInverses.push( boneInverse.toArray() );
  18878. }
  18879. return data;
  18880. }
  18881. }
  18882. /**
  18883. * An instanced version of a buffer attribute.
  18884. *
  18885. * @augments BufferAttribute
  18886. */
  18887. class InstancedBufferAttribute extends BufferAttribute {
  18888. /**
  18889. * Constructs a new instanced buffer attribute.
  18890. *
  18891. * @param {TypedArray} array - The array holding the attribute data.
  18892. * @param {number} itemSize - The item size.
  18893. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18894. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18895. */
  18896. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18897. super( array, itemSize, normalized );
  18898. /**
  18899. * This flag can be used for type testing.
  18900. *
  18901. * @type {boolean}
  18902. * @readonly
  18903. * @default true
  18904. */
  18905. this.isInstancedBufferAttribute = true;
  18906. /**
  18907. * Defines how often a value of this buffer attribute should be repeated. A
  18908. * value of one means that each value of the instanced attribute is used for
  18909. * a single instance. A value of two means that each value is used for two
  18910. * consecutive instances (and so on).
  18911. *
  18912. * @type {number}
  18913. * @default 1
  18914. */
  18915. this.meshPerAttribute = meshPerAttribute;
  18916. }
  18917. copy( source ) {
  18918. super.copy( source );
  18919. this.meshPerAttribute = source.meshPerAttribute;
  18920. return this;
  18921. }
  18922. toJSON() {
  18923. const data = super.toJSON();
  18924. data.meshPerAttribute = this.meshPerAttribute;
  18925. data.isInstancedBufferAttribute = true;
  18926. return data;
  18927. }
  18928. }
  18929. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18930. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18931. const _instanceIntersects = [];
  18932. const _box3 = /*@__PURE__*/ new Box3();
  18933. const _identity = /*@__PURE__*/ new Matrix4();
  18934. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18935. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18936. /**
  18937. * A special version of a mesh with instanced rendering support. Use
  18938. * this class if you have to render a large number of objects with the same
  18939. * geometry and material(s) but with different world transformations. The usage
  18940. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18941. * improve the overall rendering performance in your application.
  18942. *
  18943. * @augments Mesh
  18944. */
  18945. class InstancedMesh extends Mesh {
  18946. /**
  18947. * Constructs a new instanced mesh.
  18948. *
  18949. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18950. * @param {Material|Array<Material>} [material] - The mesh material.
  18951. * @param {number} count - The number of instances.
  18952. */
  18953. constructor( geometry, material, count ) {
  18954. super( geometry, material );
  18955. /**
  18956. * This flag can be used for type testing.
  18957. *
  18958. * @type {boolean}
  18959. * @readonly
  18960. * @default true
  18961. */
  18962. this.isInstancedMesh = true;
  18963. /**
  18964. * Represents the local transformation of all instances. You have to set its
  18965. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18966. * via {@link InstancedMesh#setMatrixAt}.
  18967. *
  18968. * @type {InstancedBufferAttribute}
  18969. */
  18970. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18971. /**
  18972. * Represents the color of all instances. You have to set its
  18973. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18974. * via {@link InstancedMesh#setColorAt}.
  18975. *
  18976. * @type {?InstancedBufferAttribute}
  18977. * @default null
  18978. */
  18979. this.instanceColor = null;
  18980. /**
  18981. * Represents the morph target weights of all instances. You have to set its
  18982. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18983. * via {@link InstancedMesh#setMorphAt}.
  18984. *
  18985. * @type {?DataTexture}
  18986. * @default null
  18987. */
  18988. this.morphTexture = null;
  18989. /**
  18990. * The number of instances.
  18991. *
  18992. * @type {number}
  18993. */
  18994. this.count = count;
  18995. /**
  18996. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18997. *
  18998. * @type {?Box3}
  18999. * @default null
  19000. */
  19001. this.boundingBox = null;
  19002. /**
  19003. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19004. *
  19005. * @type {?Sphere}
  19006. * @default null
  19007. */
  19008. this.boundingSphere = null;
  19009. for ( let i = 0; i < count; i ++ ) {
  19010. this.setMatrixAt( i, _identity );
  19011. }
  19012. }
  19013. /**
  19014. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19015. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19016. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19017. */
  19018. computeBoundingBox() {
  19019. const geometry = this.geometry;
  19020. const count = this.count;
  19021. if ( this.boundingBox === null ) {
  19022. this.boundingBox = new Box3();
  19023. }
  19024. if ( geometry.boundingBox === null ) {
  19025. geometry.computeBoundingBox();
  19026. }
  19027. this.boundingBox.makeEmpty();
  19028. for ( let i = 0; i < count; i ++ ) {
  19029. this.getMatrixAt( i, _instanceLocalMatrix );
  19030. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19031. this.boundingBox.union( _box3 );
  19032. }
  19033. }
  19034. /**
  19035. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19036. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19037. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19038. */
  19039. computeBoundingSphere() {
  19040. const geometry = this.geometry;
  19041. const count = this.count;
  19042. if ( this.boundingSphere === null ) {
  19043. this.boundingSphere = new Sphere();
  19044. }
  19045. if ( geometry.boundingSphere === null ) {
  19046. geometry.computeBoundingSphere();
  19047. }
  19048. this.boundingSphere.makeEmpty();
  19049. for ( let i = 0; i < count; i ++ ) {
  19050. this.getMatrixAt( i, _instanceLocalMatrix );
  19051. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19052. this.boundingSphere.union( _sphere$4 );
  19053. }
  19054. }
  19055. copy( source, recursive ) {
  19056. super.copy( source, recursive );
  19057. this.instanceMatrix.copy( source.instanceMatrix );
  19058. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19059. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19060. this.count = source.count;
  19061. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19062. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19063. return this;
  19064. }
  19065. /**
  19066. * Gets the color of the defined instance.
  19067. *
  19068. * @param {number} index - The instance index.
  19069. * @param {Color} color - The target object that is used to store the method's result.
  19070. */
  19071. getColorAt( index, color ) {
  19072. color.fromArray( this.instanceColor.array, index * 3 );
  19073. }
  19074. /**
  19075. * Gets the local transformation matrix of the defined instance.
  19076. *
  19077. * @param {number} index - The instance index.
  19078. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19079. */
  19080. getMatrixAt( index, matrix ) {
  19081. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19082. }
  19083. /**
  19084. * Gets the morph target weights of the defined instance.
  19085. *
  19086. * @param {number} index - The instance index.
  19087. * @param {Mesh} object - The target object that is used to store the method's result.
  19088. */
  19089. getMorphAt( index, object ) {
  19090. const objectInfluences = object.morphTargetInfluences;
  19091. const array = this.morphTexture.source.data.data;
  19092. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19093. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19094. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19095. objectInfluences[ i ] = array[ dataIndex + i ];
  19096. }
  19097. }
  19098. raycast( raycaster, intersects ) {
  19099. const matrixWorld = this.matrixWorld;
  19100. const raycastTimes = this.count;
  19101. _mesh$1.geometry = this.geometry;
  19102. _mesh$1.material = this.material;
  19103. if ( _mesh$1.material === undefined ) return;
  19104. // test with bounding sphere first
  19105. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19106. _sphere$4.copy( this.boundingSphere );
  19107. _sphere$4.applyMatrix4( matrixWorld );
  19108. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19109. // now test each instance
  19110. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19111. // calculate the world matrix for each instance
  19112. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19113. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19114. // the mesh represents this single instance
  19115. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19116. _mesh$1.raycast( raycaster, _instanceIntersects );
  19117. // process the result of raycast
  19118. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19119. const intersect = _instanceIntersects[ i ];
  19120. intersect.instanceId = instanceId;
  19121. intersect.object = this;
  19122. intersects.push( intersect );
  19123. }
  19124. _instanceIntersects.length = 0;
  19125. }
  19126. }
  19127. /**
  19128. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19129. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19130. *
  19131. * @param {number} index - The instance index.
  19132. * @param {Color} color - The instance color.
  19133. */
  19134. setColorAt( index, color ) {
  19135. if ( this.instanceColor === null ) {
  19136. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19137. }
  19138. color.toArray( this.instanceColor.array, index * 3 );
  19139. }
  19140. /**
  19141. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19142. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19143. *
  19144. * @param {number} index - The instance index.
  19145. * @param {Matrix4} matrix - The local transformation.
  19146. */
  19147. setMatrixAt( index, matrix ) {
  19148. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19149. }
  19150. /**
  19151. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19152. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19153. *
  19154. * @param {number} index - The instance index.
  19155. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19156. * of a single instance.
  19157. */
  19158. setMorphAt( index, object ) {
  19159. const objectInfluences = object.morphTargetInfluences;
  19160. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19161. if ( this.morphTexture === null ) {
  19162. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19163. }
  19164. const array = this.morphTexture.source.data.data;
  19165. let morphInfluencesSum = 0;
  19166. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19167. morphInfluencesSum += objectInfluences[ i ];
  19168. }
  19169. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19170. const dataIndex = len * index;
  19171. array[ dataIndex ] = morphBaseInfluence;
  19172. array.set( objectInfluences, dataIndex + 1 );
  19173. }
  19174. updateMorphTargets() {
  19175. }
  19176. /**
  19177. * Frees the GPU-related resources allocated by this instance. Call this
  19178. * method whenever this instance is no longer used in your app.
  19179. */
  19180. dispose() {
  19181. this.dispatchEvent( { type: 'dispose' } );
  19182. if ( this.morphTexture !== null ) {
  19183. this.morphTexture.dispose();
  19184. this.morphTexture = null;
  19185. }
  19186. }
  19187. }
  19188. const _vector1 = /*@__PURE__*/ new Vector3();
  19189. const _vector2 = /*@__PURE__*/ new Vector3();
  19190. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19191. /**
  19192. * A two dimensional surface that extends infinitely in 3D space, represented
  19193. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  19194. * by a unit length normal vector and a constant.
  19195. */
  19196. class Plane {
  19197. /**
  19198. * Constructs a new plane.
  19199. *
  19200. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19201. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19202. */
  19203. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19204. /**
  19205. * This flag can be used for type testing.
  19206. *
  19207. * @type {boolean}
  19208. * @readonly
  19209. * @default true
  19210. */
  19211. this.isPlane = true;
  19212. /**
  19213. * A unit length vector defining the normal of the plane.
  19214. *
  19215. * @type {Vector3}
  19216. */
  19217. this.normal = normal;
  19218. /**
  19219. * The signed distance from the origin to the plane.
  19220. *
  19221. * @type {number}
  19222. * @default 0
  19223. */
  19224. this.constant = constant;
  19225. }
  19226. /**
  19227. * Sets the plane components by copying the given values.
  19228. *
  19229. * @param {Vector3} normal - The normal.
  19230. * @param {number} constant - The constant.
  19231. * @return {Plane} A reference to this plane.
  19232. */
  19233. set( normal, constant ) {
  19234. this.normal.copy( normal );
  19235. this.constant = constant;
  19236. return this;
  19237. }
  19238. /**
  19239. * Sets the plane components by defining `x`, `y`, `z` as the
  19240. * plane normal and `w` as the constant.
  19241. *
  19242. * @param {number} x - The value for the normal's x component.
  19243. * @param {number} y - The value for the normal's y component.
  19244. * @param {number} z - The value for the normal's z component.
  19245. * @param {number} w - The constant value.
  19246. * @return {Plane} A reference to this plane.
  19247. */
  19248. setComponents( x, y, z, w ) {
  19249. this.normal.set( x, y, z );
  19250. this.constant = w;
  19251. return this;
  19252. }
  19253. /**
  19254. * Sets the plane from the given normal and coplanar point (that is a point
  19255. * that lies onto the plane).
  19256. *
  19257. * @param {Vector3} normal - The normal.
  19258. * @param {Vector3} point - A coplanar point.
  19259. * @return {Plane} A reference to this plane.
  19260. */
  19261. setFromNormalAndCoplanarPoint( normal, point ) {
  19262. this.normal.copy( normal );
  19263. this.constant = - point.dot( this.normal );
  19264. return this;
  19265. }
  19266. /**
  19267. * Sets the plane from three coplanar points. The winding order is
  19268. * assumed to be counter-clockwise, and determines the direction of
  19269. * the plane normal.
  19270. *
  19271. * @param {Vector3} a - The first coplanar point.
  19272. * @param {Vector3} b - The second coplanar point.
  19273. * @param {Vector3} c - The third coplanar point.
  19274. * @return {Plane} A reference to this plane.
  19275. */
  19276. setFromCoplanarPoints( a, b, c ) {
  19277. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19278. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19279. this.setFromNormalAndCoplanarPoint( normal, a );
  19280. return this;
  19281. }
  19282. /**
  19283. * Copies the values of the given plane to this instance.
  19284. *
  19285. * @param {Plane} plane - The plane to copy.
  19286. * @return {Plane} A reference to this plane.
  19287. */
  19288. copy( plane ) {
  19289. this.normal.copy( plane.normal );
  19290. this.constant = plane.constant;
  19291. return this;
  19292. }
  19293. /**
  19294. * Normalizes the plane normal and adjusts the constant accordingly.
  19295. *
  19296. * @return {Plane} A reference to this plane.
  19297. */
  19298. normalize() {
  19299. // Note: will lead to a divide by zero if the plane is invalid.
  19300. const inverseNormalLength = 1.0 / this.normal.length();
  19301. this.normal.multiplyScalar( inverseNormalLength );
  19302. this.constant *= inverseNormalLength;
  19303. return this;
  19304. }
  19305. /**
  19306. * Negates both the plane normal and the constant.
  19307. *
  19308. * @return {Plane} A reference to this plane.
  19309. */
  19310. negate() {
  19311. this.constant *= -1;
  19312. this.normal.negate();
  19313. return this;
  19314. }
  19315. /**
  19316. * Returns the signed distance from the given point to this plane.
  19317. *
  19318. * @param {Vector3} point - The point to compute the distance for.
  19319. * @return {number} The signed distance.
  19320. */
  19321. distanceToPoint( point ) {
  19322. return this.normal.dot( point ) + this.constant;
  19323. }
  19324. /**
  19325. * Returns the signed distance from the given sphere to this plane.
  19326. *
  19327. * @param {Sphere} sphere - The sphere to compute the distance for.
  19328. * @return {number} The signed distance.
  19329. */
  19330. distanceToSphere( sphere ) {
  19331. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19332. }
  19333. /**
  19334. * Projects a the given point onto the plane.
  19335. *
  19336. * @param {Vector3} point - The point to project.
  19337. * @param {Vector3} target - The target vector that is used to store the method's result.
  19338. * @return {Vector3} The projected point on the plane.
  19339. */
  19340. projectPoint( point, target ) {
  19341. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19342. }
  19343. /**
  19344. * Returns the intersection point of the passed line and the plane. Returns
  19345. * `null` if the line does not intersect. Returns the line's starting point if
  19346. * the line is coplanar with the plane.
  19347. *
  19348. * @param {Line3} line - The line to compute the intersection for.
  19349. * @param {Vector3} target - The target vector that is used to store the method's result.
  19350. * @return {?Vector3} The intersection point.
  19351. */
  19352. intersectLine( line, target ) {
  19353. const direction = line.delta( _vector1 );
  19354. const denominator = this.normal.dot( direction );
  19355. if ( denominator === 0 ) {
  19356. // line is coplanar, return origin
  19357. if ( this.distanceToPoint( line.start ) === 0 ) {
  19358. return target.copy( line.start );
  19359. }
  19360. // Unsure if this is the correct method to handle this case.
  19361. return null;
  19362. }
  19363. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19364. if ( t < 0 || t > 1 ) {
  19365. return null;
  19366. }
  19367. return target.copy( line.start ).addScaledVector( direction, t );
  19368. }
  19369. /**
  19370. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19371. *
  19372. * @param {Line3} line - The line to test.
  19373. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19374. */
  19375. intersectsLine( line ) {
  19376. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19377. const startSign = this.distanceToPoint( line.start );
  19378. const endSign = this.distanceToPoint( line.end );
  19379. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19380. }
  19381. /**
  19382. * Returns `true` if the given bounding box intersects with the plane.
  19383. *
  19384. * @param {Box3} box - The bounding box to test.
  19385. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19386. */
  19387. intersectsBox( box ) {
  19388. return box.intersectsPlane( this );
  19389. }
  19390. /**
  19391. * Returns `true` if the given bounding sphere intersects with the plane.
  19392. *
  19393. * @param {Sphere} sphere - The bounding sphere to test.
  19394. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19395. */
  19396. intersectsSphere( sphere ) {
  19397. return sphere.intersectsPlane( this );
  19398. }
  19399. /**
  19400. * Returns a coplanar vector to the plane, by calculating the
  19401. * projection of the normal at the origin onto the plane.
  19402. *
  19403. * @param {Vector3} target - The target vector that is used to store the method's result.
  19404. * @return {Vector3} The coplanar point.
  19405. */
  19406. coplanarPoint( target ) {
  19407. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19408. }
  19409. /**
  19410. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19411. *
  19412. * The optional normal matrix can be pre-computed like so:
  19413. * ```js
  19414. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19415. * ```
  19416. *
  19417. * @param {Matrix4} matrix - The transformation matrix.
  19418. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19419. * @return {Plane} A reference to this plane.
  19420. */
  19421. applyMatrix4( matrix, optionalNormalMatrix ) {
  19422. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19423. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19424. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19425. this.constant = - referencePoint.dot( normal );
  19426. return this;
  19427. }
  19428. /**
  19429. * Translates the plane by the distance defined by the given offset vector.
  19430. * Note that this only affects the plane constant and will not affect the normal vector.
  19431. *
  19432. * @param {Vector3} offset - The offset vector.
  19433. * @return {Plane} A reference to this plane.
  19434. */
  19435. translate( offset ) {
  19436. this.constant -= offset.dot( this.normal );
  19437. return this;
  19438. }
  19439. /**
  19440. * Returns `true` if this plane is equal with the given one.
  19441. *
  19442. * @param {Plane} plane - The plane to test for equality.
  19443. * @return {boolean} Whether this plane is equal with the given one.
  19444. */
  19445. equals( plane ) {
  19446. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19447. }
  19448. /**
  19449. * Returns a new plane with copied values from this instance.
  19450. *
  19451. * @return {Plane} A clone of this instance.
  19452. */
  19453. clone() {
  19454. return new this.constructor().copy( this );
  19455. }
  19456. }
  19457. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19458. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19459. const _vector$6 = /*@__PURE__*/ new Vector3();
  19460. /**
  19461. * Frustums are used to determine what is inside the camera's field of view.
  19462. * They help speed up the rendering process - objects which lie outside a camera's
  19463. * frustum can safely be excluded from rendering.
  19464. *
  19465. * This class is mainly intended for use internally by a renderer.
  19466. */
  19467. class Frustum {
  19468. /**
  19469. * Constructs a new frustum.
  19470. *
  19471. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19472. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19473. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19474. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19475. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19476. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19477. */
  19478. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19479. /**
  19480. * This array holds the planes that enclose the frustum.
  19481. *
  19482. * @type {Array<Plane>}
  19483. */
  19484. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19485. }
  19486. /**
  19487. * Sets the frustum planes by copying the given planes.
  19488. *
  19489. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19490. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19491. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19492. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19493. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19494. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19495. * @return {Frustum} A reference to this frustum.
  19496. */
  19497. set( p0, p1, p2, p3, p4, p5 ) {
  19498. const planes = this.planes;
  19499. planes[ 0 ].copy( p0 );
  19500. planes[ 1 ].copy( p1 );
  19501. planes[ 2 ].copy( p2 );
  19502. planes[ 3 ].copy( p3 );
  19503. planes[ 4 ].copy( p4 );
  19504. planes[ 5 ].copy( p5 );
  19505. return this;
  19506. }
  19507. /**
  19508. * Copies the values of the given frustum to this instance.
  19509. *
  19510. * @param {Frustum} frustum - The frustum to copy.
  19511. * @return {Frustum} A reference to this frustum.
  19512. */
  19513. copy( frustum ) {
  19514. const planes = this.planes;
  19515. for ( let i = 0; i < 6; i ++ ) {
  19516. planes[ i ].copy( frustum.planes[ i ] );
  19517. }
  19518. return this;
  19519. }
  19520. /**
  19521. * Sets the frustum planes from the given projection matrix.
  19522. *
  19523. * @param {Matrix4} m - The projection matrix.
  19524. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19525. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19526. * @return {Frustum} A reference to this frustum.
  19527. */
  19528. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19529. const planes = this.planes;
  19530. const me = m.elements;
  19531. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19532. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19533. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19534. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19535. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19536. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19537. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19538. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19539. if ( reversedDepth ) {
  19540. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19541. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19542. } else {
  19543. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19544. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19545. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19546. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19547. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19548. } else {
  19549. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19550. }
  19551. }
  19552. return this;
  19553. }
  19554. /**
  19555. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19556. *
  19557. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19558. *
  19559. * @param {Object3D} object - The 3D object to test.
  19560. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19561. */
  19562. intersectsObject( object ) {
  19563. if ( object.boundingSphere !== undefined ) {
  19564. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19565. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19566. } else {
  19567. const geometry = object.geometry;
  19568. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19569. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19570. }
  19571. return this.intersectsSphere( _sphere$3 );
  19572. }
  19573. /**
  19574. * Returns `true` if the given sprite is intersecting this frustum.
  19575. *
  19576. * @param {Sprite} sprite - The sprite to test.
  19577. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19578. */
  19579. intersectsSprite( sprite ) {
  19580. _sphere$3.center.set( 0, 0, 0 );
  19581. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19582. _sphere$3.radius = 0.7071067811865476 + offset;
  19583. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19584. return this.intersectsSphere( _sphere$3 );
  19585. }
  19586. /**
  19587. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19588. *
  19589. * @param {Sphere} sphere - The bounding sphere to test.
  19590. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19591. */
  19592. intersectsSphere( sphere ) {
  19593. const planes = this.planes;
  19594. const center = sphere.center;
  19595. const negRadius = - sphere.radius;
  19596. for ( let i = 0; i < 6; i ++ ) {
  19597. const distance = planes[ i ].distanceToPoint( center );
  19598. if ( distance < negRadius ) {
  19599. return false;
  19600. }
  19601. }
  19602. return true;
  19603. }
  19604. /**
  19605. * Returns `true` if the given bounding box is intersecting this frustum.
  19606. *
  19607. * @param {Box3} box - The bounding box to test.
  19608. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19609. */
  19610. intersectsBox( box ) {
  19611. const planes = this.planes;
  19612. for ( let i = 0; i < 6; i ++ ) {
  19613. const plane = planes[ i ];
  19614. // corner at max distance
  19615. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19616. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19617. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19618. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19619. return false;
  19620. }
  19621. }
  19622. return true;
  19623. }
  19624. /**
  19625. * Returns `true` if the given point lies within the frustum.
  19626. *
  19627. * @param {Vector3} point - The point to test.
  19628. * @return {boolean} Whether the point lies within this frustum or not.
  19629. */
  19630. containsPoint( point ) {
  19631. const planes = this.planes;
  19632. for ( let i = 0; i < 6; i ++ ) {
  19633. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19634. return false;
  19635. }
  19636. }
  19637. return true;
  19638. }
  19639. /**
  19640. * Returns a new frustum with copied values from this instance.
  19641. *
  19642. * @return {Frustum} A clone of this instance.
  19643. */
  19644. clone() {
  19645. return new this.constructor().copy( this );
  19646. }
  19647. }
  19648. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19649. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19650. /**
  19651. * FrustumArray is used to determine if an object is visible in at least one camera
  19652. * from an array of cameras. This is particularly useful for multi-view renderers.
  19653. */
  19654. class FrustumArray {
  19655. /**
  19656. * Constructs a new frustum array.
  19657. *
  19658. */
  19659. constructor() {
  19660. /**
  19661. * The coordinate system to use.
  19662. *
  19663. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19664. * @default WebGLCoordinateSystem
  19665. */
  19666. this.coordinateSystem = WebGLCoordinateSystem;
  19667. }
  19668. /**
  19669. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19670. * from the camera array.
  19671. *
  19672. * @param {Object3D} object - The 3D object to test.
  19673. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19674. * @return {boolean} Whether the 3D object is visible in any camera.
  19675. */
  19676. intersectsObject( object, cameraArray ) {
  19677. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19678. return false;
  19679. }
  19680. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19681. const camera = cameraArray.cameras[ i ];
  19682. _projScreenMatrix$2.multiplyMatrices(
  19683. camera.projectionMatrix,
  19684. camera.matrixWorldInverse
  19685. );
  19686. _frustum$1.setFromProjectionMatrix(
  19687. _projScreenMatrix$2,
  19688. camera.coordinateSystem,
  19689. camera.reversedDepth
  19690. );
  19691. if ( _frustum$1.intersectsObject( object ) ) {
  19692. return true; // Object is visible in at least one camera
  19693. }
  19694. }
  19695. return false; // Not visible in any camera
  19696. }
  19697. /**
  19698. * Returns `true` if the given sprite is intersecting any frustum
  19699. * from the camera array.
  19700. *
  19701. * @param {Sprite} sprite - The sprite to test.
  19702. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19703. * @return {boolean} Whether the sprite is visible in any camera.
  19704. */
  19705. intersectsSprite( sprite, cameraArray ) {
  19706. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19707. return false;
  19708. }
  19709. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19710. const camera = cameraArray.cameras[ i ];
  19711. _projScreenMatrix$2.multiplyMatrices(
  19712. camera.projectionMatrix,
  19713. camera.matrixWorldInverse
  19714. );
  19715. _frustum$1.setFromProjectionMatrix(
  19716. _projScreenMatrix$2,
  19717. camera.coordinateSystem,
  19718. camera.reversedDepth
  19719. );
  19720. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19721. return true; // Sprite is visible in at least one camera
  19722. }
  19723. }
  19724. return false; // Not visible in any camera
  19725. }
  19726. /**
  19727. * Returns `true` if the given bounding sphere is intersecting any frustum
  19728. * from the camera array.
  19729. *
  19730. * @param {Sphere} sphere - The bounding sphere to test.
  19731. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19732. * @return {boolean} Whether the sphere is visible in any camera.
  19733. */
  19734. intersectsSphere( sphere, cameraArray ) {
  19735. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19736. return false;
  19737. }
  19738. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19739. const camera = cameraArray.cameras[ i ];
  19740. _projScreenMatrix$2.multiplyMatrices(
  19741. camera.projectionMatrix,
  19742. camera.matrixWorldInverse
  19743. );
  19744. _frustum$1.setFromProjectionMatrix(
  19745. _projScreenMatrix$2,
  19746. camera.coordinateSystem,
  19747. camera.reversedDepth
  19748. );
  19749. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19750. return true; // Sphere is visible in at least one camera
  19751. }
  19752. }
  19753. return false; // Not visible in any camera
  19754. }
  19755. /**
  19756. * Returns `true` if the given bounding box is intersecting any frustum
  19757. * from the camera array.
  19758. *
  19759. * @param {Box3} box - The bounding box to test.
  19760. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19761. * @return {boolean} Whether the box is visible in any camera.
  19762. */
  19763. intersectsBox( box, cameraArray ) {
  19764. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19765. return false;
  19766. }
  19767. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19768. const camera = cameraArray.cameras[ i ];
  19769. _projScreenMatrix$2.multiplyMatrices(
  19770. camera.projectionMatrix,
  19771. camera.matrixWorldInverse
  19772. );
  19773. _frustum$1.setFromProjectionMatrix(
  19774. _projScreenMatrix$2,
  19775. camera.coordinateSystem,
  19776. camera.reversedDepth
  19777. );
  19778. if ( _frustum$1.intersectsBox( box ) ) {
  19779. return true; // Box is visible in at least one camera
  19780. }
  19781. }
  19782. return false; // Not visible in any camera
  19783. }
  19784. /**
  19785. * Returns `true` if the given point lies within any frustum
  19786. * from the camera array.
  19787. *
  19788. * @param {Vector3} point - The point to test.
  19789. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19790. * @return {boolean} Whether the point is visible in any camera.
  19791. */
  19792. containsPoint( point, cameraArray ) {
  19793. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19794. return false;
  19795. }
  19796. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19797. const camera = cameraArray.cameras[ i ];
  19798. _projScreenMatrix$2.multiplyMatrices(
  19799. camera.projectionMatrix,
  19800. camera.matrixWorldInverse
  19801. );
  19802. _frustum$1.setFromProjectionMatrix(
  19803. _projScreenMatrix$2,
  19804. camera.coordinateSystem,
  19805. camera.reversedDepth
  19806. );
  19807. if ( _frustum$1.containsPoint( point ) ) {
  19808. return true; // Point is visible in at least one camera
  19809. }
  19810. }
  19811. return false; // Not visible in any camera
  19812. }
  19813. /**
  19814. * Returns a new frustum array with copied values from this instance.
  19815. *
  19816. * @return {FrustumArray} A clone of this instance.
  19817. */
  19818. clone() {
  19819. return new FrustumArray();
  19820. }
  19821. }
  19822. function ascIdSort( a, b ) {
  19823. return a - b;
  19824. }
  19825. function sortOpaque( a, b ) {
  19826. return a.z - b.z;
  19827. }
  19828. function sortTransparent( a, b ) {
  19829. return b.z - a.z;
  19830. }
  19831. class MultiDrawRenderList {
  19832. constructor() {
  19833. this.index = 0;
  19834. this.pool = [];
  19835. this.list = [];
  19836. }
  19837. push( start, count, z, index ) {
  19838. const pool = this.pool;
  19839. const list = this.list;
  19840. if ( this.index >= pool.length ) {
  19841. pool.push( {
  19842. start: -1,
  19843. count: -1,
  19844. z: -1,
  19845. index: -1,
  19846. } );
  19847. }
  19848. const item = pool[ this.index ];
  19849. list.push( item );
  19850. this.index ++;
  19851. item.start = start;
  19852. item.count = count;
  19853. item.z = z;
  19854. item.index = index;
  19855. }
  19856. reset() {
  19857. this.list.length = 0;
  19858. this.index = 0;
  19859. }
  19860. }
  19861. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19862. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19863. const _frustum = /*@__PURE__*/ new Frustum();
  19864. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19865. const _box$1 = /*@__PURE__*/ new Box3();
  19866. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19867. const _vector$5 = /*@__PURE__*/ new Vector3();
  19868. const _forward$1 = /*@__PURE__*/ new Vector3();
  19869. const _temp = /*@__PURE__*/ new Vector3();
  19870. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19871. const _mesh = /*@__PURE__*/ new Mesh();
  19872. const _batchIntersects = [];
  19873. // copies data from attribute "src" into "target" starting at "targetOffset"
  19874. function copyAttributeData( src, target, targetOffset = 0 ) {
  19875. const itemSize = target.itemSize;
  19876. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19877. // use the component getters and setters if the array data cannot
  19878. // be copied directly
  19879. const vertexCount = src.count;
  19880. for ( let i = 0; i < vertexCount; i ++ ) {
  19881. for ( let c = 0; c < itemSize; c ++ ) {
  19882. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19883. }
  19884. }
  19885. } else {
  19886. // faster copy approach using typed array set function
  19887. target.array.set( src.array, targetOffset * itemSize );
  19888. }
  19889. target.needsUpdate = true;
  19890. }
  19891. // safely copies array contents to a potentially smaller array
  19892. function copyArrayContents( src, target ) {
  19893. if ( src.constructor !== target.constructor ) {
  19894. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19895. const len = Math.min( src.length, target.length );
  19896. for ( let i = 0; i < len; i ++ ) {
  19897. target[ i ] = src[ i ];
  19898. }
  19899. } else {
  19900. // if the arrays use the same data layout we can use a fast block copy
  19901. const len = Math.min( src.length, target.length );
  19902. target.set( new src.constructor( src.buffer, 0, len ) );
  19903. }
  19904. }
  19905. /**
  19906. * A special version of a mesh with multi draw batch rendering support. Use
  19907. * this class if you have to render a large number of objects with the same
  19908. * material but with different geometries or world transformations. The usage of
  19909. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19910. * rendering performance in your application.
  19911. *
  19912. * ```js
  19913. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19914. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19915. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19916. *
  19917. * // initialize and add geometries into the batched mesh
  19918. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19919. * const boxGeometryId = batchedMesh.addGeometry( box );
  19920. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19921. *
  19922. * // create instances of those geometries
  19923. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19924. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19925. *
  19926. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19927. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19928. *
  19929. * // position the geometries
  19930. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19931. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19932. *
  19933. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19934. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19935. *
  19936. * scene.add( batchedMesh );
  19937. * ```
  19938. *
  19939. * @augments Mesh
  19940. */
  19941. class BatchedMesh extends Mesh {
  19942. /**
  19943. * Constructs a new batched mesh.
  19944. *
  19945. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19946. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19947. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19948. * @param {Material|Array<Material>} [material] - The mesh material.
  19949. */
  19950. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19951. super( new BufferGeometry(), material );
  19952. /**
  19953. * This flag can be used for type testing.
  19954. *
  19955. * @type {boolean}
  19956. * @readonly
  19957. * @default true
  19958. */
  19959. this.isBatchedMesh = true;
  19960. /**
  19961. * When set ot `true`, the individual objects of a batch are frustum culled.
  19962. *
  19963. * @type {boolean}
  19964. * @default true
  19965. */
  19966. this.perObjectFrustumCulled = true;
  19967. /**
  19968. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19969. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19970. * rendered front to back.
  19971. *
  19972. * @type {boolean}
  19973. * @default true
  19974. */
  19975. this.sortObjects = true;
  19976. /**
  19977. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19978. *
  19979. * @type {?Box3}
  19980. * @default null
  19981. */
  19982. this.boundingBox = null;
  19983. /**
  19984. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19985. *
  19986. * @type {?Sphere}
  19987. * @default null
  19988. */
  19989. this.boundingSphere = null;
  19990. /**
  19991. * Takes a sort a function that is run before render. The function takes a list of instances to
  19992. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19993. * sort with.
  19994. *
  19995. * @type {?Function}
  19996. * @default null
  19997. */
  19998. this.customSort = null;
  19999. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20000. this._instanceInfo = [];
  20001. this._geometryInfo = [];
  20002. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20003. this._availableInstanceIds = [];
  20004. this._availableGeometryIds = [];
  20005. // used to track where the next point is that geometry should be inserted
  20006. this._nextIndexStart = 0;
  20007. this._nextVertexStart = 0;
  20008. this._geometryCount = 0;
  20009. // flags
  20010. this._visibilityChanged = true;
  20011. this._geometryInitialized = false;
  20012. // cached user options
  20013. this._maxInstanceCount = maxInstanceCount;
  20014. this._maxVertexCount = maxVertexCount;
  20015. this._maxIndexCount = maxIndexCount;
  20016. // buffers for multi draw
  20017. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20018. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20019. this._multiDrawCount = 0;
  20020. this._multiDrawInstances = null;
  20021. // Local matrix per geometry by using data texture
  20022. this._matricesTexture = null;
  20023. this._indirectTexture = null;
  20024. this._colorsTexture = null;
  20025. this._initMatricesTexture();
  20026. this._initIndirectTexture();
  20027. }
  20028. /**
  20029. * The maximum number of individual instances that can be stored in the batch.
  20030. *
  20031. * @type {number}
  20032. * @readonly
  20033. */
  20034. get maxInstanceCount() {
  20035. return this._maxInstanceCount;
  20036. }
  20037. /**
  20038. * The instance count.
  20039. *
  20040. * @type {number}
  20041. * @readonly
  20042. */
  20043. get instanceCount() {
  20044. return this._instanceInfo.length - this._availableInstanceIds.length;
  20045. }
  20046. /**
  20047. * The number of unused vertices.
  20048. *
  20049. * @type {number}
  20050. * @readonly
  20051. */
  20052. get unusedVertexCount() {
  20053. return this._maxVertexCount - this._nextVertexStart;
  20054. }
  20055. /**
  20056. * The number of unused indices.
  20057. *
  20058. * @type {number}
  20059. * @readonly
  20060. */
  20061. get unusedIndexCount() {
  20062. return this._maxIndexCount - this._nextIndexStart;
  20063. }
  20064. _initMatricesTexture() {
  20065. // layout (1 matrix = 4 pixels)
  20066. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20067. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20068. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20069. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20070. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20071. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20072. size = Math.ceil( size / 4 ) * 4;
  20073. size = Math.max( size, 4 );
  20074. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20075. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20076. this._matricesTexture = matricesTexture;
  20077. }
  20078. _initIndirectTexture() {
  20079. let size = Math.sqrt( this._maxInstanceCount );
  20080. size = Math.ceil( size );
  20081. const indirectArray = new Uint32Array( size * size );
  20082. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20083. this._indirectTexture = indirectTexture;
  20084. }
  20085. _initColorsTexture() {
  20086. let size = Math.sqrt( this._maxInstanceCount );
  20087. size = Math.ceil( size );
  20088. // 4 floats per RGBA pixel initialized to white
  20089. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20090. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20091. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20092. this._colorsTexture = colorsTexture;
  20093. }
  20094. _initializeGeometry( reference ) {
  20095. const geometry = this.geometry;
  20096. const maxVertexCount = this._maxVertexCount;
  20097. const maxIndexCount = this._maxIndexCount;
  20098. if ( this._geometryInitialized === false ) {
  20099. for ( const attributeName in reference.attributes ) {
  20100. const srcAttribute = reference.getAttribute( attributeName );
  20101. const { array, itemSize, normalized } = srcAttribute;
  20102. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20103. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20104. geometry.setAttribute( attributeName, dstAttribute );
  20105. }
  20106. if ( reference.getIndex() !== null ) {
  20107. // Reserve last u16 index for primitive restart.
  20108. const indexArray = maxVertexCount > 65535
  20109. ? new Uint32Array( maxIndexCount )
  20110. : new Uint16Array( maxIndexCount );
  20111. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20112. }
  20113. this._geometryInitialized = true;
  20114. }
  20115. }
  20116. // Make sure the geometry is compatible with the existing combined geometry attributes
  20117. _validateGeometry( geometry ) {
  20118. // check to ensure the geometries are using consistent attributes and indices
  20119. const batchGeometry = this.geometry;
  20120. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20121. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20122. }
  20123. for ( const attributeName in batchGeometry.attributes ) {
  20124. if ( ! geometry.hasAttribute( attributeName ) ) {
  20125. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20126. }
  20127. const srcAttribute = geometry.getAttribute( attributeName );
  20128. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20129. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20130. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20131. }
  20132. }
  20133. }
  20134. /**
  20135. * Validates the instance defined by the given ID.
  20136. *
  20137. * @param {number} instanceId - The instance to validate.
  20138. */
  20139. validateInstanceId( instanceId ) {
  20140. const instanceInfo = this._instanceInfo;
  20141. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20142. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20143. }
  20144. }
  20145. /**
  20146. * Validates the geometry defined by the given ID.
  20147. *
  20148. * @param {number} geometryId - The geometry to validate.
  20149. */
  20150. validateGeometryId( geometryId ) {
  20151. const geometryInfoList = this._geometryInfo;
  20152. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20153. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20154. }
  20155. }
  20156. /**
  20157. * Takes a sort a function that is run before render. The function takes a list of instances to
  20158. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20159. *
  20160. * @param {Function} func - The custom sort function.
  20161. * @return {BatchedMesh} A reference to this batched mesh.
  20162. */
  20163. setCustomSort( func ) {
  20164. this.customSort = func;
  20165. return this;
  20166. }
  20167. /**
  20168. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20169. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20170. * otherwise they are `null`.
  20171. */
  20172. computeBoundingBox() {
  20173. if ( this.boundingBox === null ) {
  20174. this.boundingBox = new Box3();
  20175. }
  20176. const boundingBox = this.boundingBox;
  20177. const instanceInfo = this._instanceInfo;
  20178. boundingBox.makeEmpty();
  20179. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20180. if ( instanceInfo[ i ].active === false ) continue;
  20181. const geometryId = instanceInfo[ i ].geometryIndex;
  20182. this.getMatrixAt( i, _matrix$1 );
  20183. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20184. boundingBox.union( _box$1 );
  20185. }
  20186. }
  20187. /**
  20188. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20189. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20190. * otherwise they are `null`.
  20191. */
  20192. computeBoundingSphere() {
  20193. if ( this.boundingSphere === null ) {
  20194. this.boundingSphere = new Sphere();
  20195. }
  20196. const boundingSphere = this.boundingSphere;
  20197. const instanceInfo = this._instanceInfo;
  20198. boundingSphere.makeEmpty();
  20199. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20200. if ( instanceInfo[ i ].active === false ) continue;
  20201. const geometryId = instanceInfo[ i ].geometryIndex;
  20202. this.getMatrixAt( i, _matrix$1 );
  20203. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20204. boundingSphere.union( _sphere$2 );
  20205. }
  20206. }
  20207. /**
  20208. * Adds a new instance to the batch using the geometry of the given ID and returns
  20209. * a new id referring to the new instance to be used by other functions.
  20210. *
  20211. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20212. * @return {number} The instance ID.
  20213. */
  20214. addInstance( geometryId ) {
  20215. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20216. // ensure we're not over geometry
  20217. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20218. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20219. }
  20220. const instanceInfo = {
  20221. visible: true,
  20222. active: true,
  20223. geometryIndex: geometryId,
  20224. };
  20225. let drawId = null;
  20226. // Prioritize using previously freed instance ids
  20227. if ( this._availableInstanceIds.length > 0 ) {
  20228. this._availableInstanceIds.sort( ascIdSort );
  20229. drawId = this._availableInstanceIds.shift();
  20230. this._instanceInfo[ drawId ] = instanceInfo;
  20231. } else {
  20232. drawId = this._instanceInfo.length;
  20233. this._instanceInfo.push( instanceInfo );
  20234. }
  20235. const matricesTexture = this._matricesTexture;
  20236. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20237. matricesTexture.needsUpdate = true;
  20238. const colorsTexture = this._colorsTexture;
  20239. if ( colorsTexture ) {
  20240. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20241. colorsTexture.needsUpdate = true;
  20242. }
  20243. this._visibilityChanged = true;
  20244. return drawId;
  20245. }
  20246. /**
  20247. * Adds the given geometry to the batch and returns the associated
  20248. * geometry id referring to it to be used in other functions.
  20249. *
  20250. * @param {BufferGeometry} geometry - The geometry to add.
  20251. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20252. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20253. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20254. * Defaults to the length of the given geometry vertex buffer.
  20255. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20256. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20257. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20258. * the length of the given geometry index buffer.
  20259. * @return {number} The geometry ID.
  20260. */
  20261. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20262. this._initializeGeometry( geometry );
  20263. this._validateGeometry( geometry );
  20264. const geometryInfo = {
  20265. // geometry information
  20266. vertexStart: -1,
  20267. vertexCount: -1,
  20268. reservedVertexCount: -1,
  20269. indexStart: -1,
  20270. indexCount: -1,
  20271. reservedIndexCount: -1,
  20272. // draw range information
  20273. start: -1,
  20274. count: -1,
  20275. // state
  20276. boundingBox: null,
  20277. boundingSphere: null,
  20278. active: true,
  20279. };
  20280. const geometryInfoList = this._geometryInfo;
  20281. geometryInfo.vertexStart = this._nextVertexStart;
  20282. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20283. const index = geometry.getIndex();
  20284. const hasIndex = index !== null;
  20285. if ( hasIndex ) {
  20286. geometryInfo.indexStart = this._nextIndexStart;
  20287. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20288. }
  20289. if (
  20290. geometryInfo.indexStart !== -1 &&
  20291. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20292. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20293. ) {
  20294. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20295. }
  20296. // update id
  20297. let geometryId;
  20298. if ( this._availableGeometryIds.length > 0 ) {
  20299. this._availableGeometryIds.sort( ascIdSort );
  20300. geometryId = this._availableGeometryIds.shift();
  20301. geometryInfoList[ geometryId ] = geometryInfo;
  20302. } else {
  20303. geometryId = this._geometryCount;
  20304. this._geometryCount ++;
  20305. geometryInfoList.push( geometryInfo );
  20306. }
  20307. // update the geometry
  20308. this.setGeometryAt( geometryId, geometry );
  20309. // increment the next geometry position
  20310. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20311. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20312. return geometryId;
  20313. }
  20314. /**
  20315. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20316. * is not enough space reserved for geometry. Calling this will change all instances that are
  20317. * rendering that geometry.
  20318. *
  20319. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20320. * @param {BufferGeometry} geometry - The new geometry.
  20321. * @return {number} The geometry ID.
  20322. */
  20323. setGeometryAt( geometryId, geometry ) {
  20324. if ( geometryId >= this._geometryCount ) {
  20325. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20326. }
  20327. this._validateGeometry( geometry );
  20328. const batchGeometry = this.geometry;
  20329. const hasIndex = batchGeometry.getIndex() !== null;
  20330. const dstIndex = batchGeometry.getIndex();
  20331. const srcIndex = geometry.getIndex();
  20332. const geometryInfo = this._geometryInfo[ geometryId ];
  20333. if (
  20334. hasIndex &&
  20335. srcIndex.count > geometryInfo.reservedIndexCount ||
  20336. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20337. ) {
  20338. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20339. }
  20340. // copy geometry buffer data over
  20341. const vertexStart = geometryInfo.vertexStart;
  20342. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20343. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20344. for ( const attributeName in batchGeometry.attributes ) {
  20345. // copy attribute data
  20346. const srcAttribute = geometry.getAttribute( attributeName );
  20347. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20348. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20349. // fill the rest in with zeroes
  20350. const itemSize = srcAttribute.itemSize;
  20351. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20352. const index = vertexStart + i;
  20353. for ( let c = 0; c < itemSize; c ++ ) {
  20354. dstAttribute.setComponent( index, c, 0 );
  20355. }
  20356. }
  20357. dstAttribute.needsUpdate = true;
  20358. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20359. }
  20360. // copy index
  20361. if ( hasIndex ) {
  20362. const indexStart = geometryInfo.indexStart;
  20363. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20364. geometryInfo.indexCount = geometry.getIndex().count;
  20365. // copy index data over
  20366. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20367. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20368. }
  20369. // fill the rest in with zeroes
  20370. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20371. dstIndex.setX( indexStart + i, vertexStart );
  20372. }
  20373. dstIndex.needsUpdate = true;
  20374. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20375. }
  20376. // update the draw range
  20377. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20378. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20379. // store the bounding boxes
  20380. geometryInfo.boundingBox = null;
  20381. if ( geometry.boundingBox !== null ) {
  20382. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20383. }
  20384. geometryInfo.boundingSphere = null;
  20385. if ( geometry.boundingSphere !== null ) {
  20386. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20387. }
  20388. this._visibilityChanged = true;
  20389. return geometryId;
  20390. }
  20391. /**
  20392. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20393. * this geometry will also be removed as a side effect.
  20394. *
  20395. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20396. * @return {BatchedMesh} A reference to this batched mesh.
  20397. */
  20398. deleteGeometry( geometryId ) {
  20399. const geometryInfoList = this._geometryInfo;
  20400. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20401. return this;
  20402. }
  20403. // delete any instances associated with this geometry
  20404. const instanceInfo = this._instanceInfo;
  20405. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20406. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20407. this.deleteInstance( i );
  20408. }
  20409. }
  20410. geometryInfoList[ geometryId ].active = false;
  20411. this._availableGeometryIds.push( geometryId );
  20412. this._visibilityChanged = true;
  20413. return this;
  20414. }
  20415. /**
  20416. * Deletes an existing instance from the batch using the given ID.
  20417. *
  20418. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20419. * @return {BatchedMesh} A reference to this batched mesh.
  20420. */
  20421. deleteInstance( instanceId ) {
  20422. this.validateInstanceId( instanceId );
  20423. this._instanceInfo[ instanceId ].active = false;
  20424. this._availableInstanceIds.push( instanceId );
  20425. this._visibilityChanged = true;
  20426. return this;
  20427. }
  20428. /**
  20429. * Repacks the sub geometries in [name] to remove any unused space remaining from
  20430. * previously deleted geometry, freeing up space to add new geometry.
  20431. *
  20432. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20433. * @return {BatchedMesh} A reference to this batched mesh.
  20434. */
  20435. optimize() {
  20436. // track the next indices to copy data to
  20437. let nextVertexStart = 0;
  20438. let nextIndexStart = 0;
  20439. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20440. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20441. const geometryInfoList = this._geometryInfo;
  20442. const indices = geometryInfoList
  20443. .map( ( e, i ) => i )
  20444. .sort( ( a, b ) => {
  20445. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20446. } );
  20447. const geometry = this.geometry;
  20448. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20449. // if a geometry range is inactive then don't copy anything
  20450. const index = indices[ i ];
  20451. const geometryInfo = geometryInfoList[ index ];
  20452. if ( geometryInfo.active === false ) {
  20453. continue;
  20454. }
  20455. // if a geometry contains an index buffer then shift it, as well
  20456. if ( geometry.index !== null ) {
  20457. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20458. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20459. const index = geometry.index;
  20460. const array = index.array;
  20461. // shift the index pointers based on how the vertex data will shift
  20462. // adjusting the index must happen first so the original vertex start value is available
  20463. const elementDelta = nextVertexStart - vertexStart;
  20464. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20465. array[ j ] = array[ j ] + elementDelta;
  20466. }
  20467. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20468. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20469. geometryInfo.indexStart = nextIndexStart;
  20470. }
  20471. nextIndexStart += geometryInfo.reservedIndexCount;
  20472. }
  20473. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20474. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20475. const { vertexStart, reservedVertexCount } = geometryInfo;
  20476. const attributes = geometry.attributes;
  20477. for ( const key in attributes ) {
  20478. const attribute = attributes[ key ];
  20479. const { array, itemSize } = attribute;
  20480. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20481. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20482. }
  20483. geometryInfo.vertexStart = nextVertexStart;
  20484. }
  20485. nextVertexStart += geometryInfo.reservedVertexCount;
  20486. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20487. // step the next geometry points to the shifted position
  20488. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20489. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20490. }
  20491. return this;
  20492. }
  20493. /**
  20494. * Returns the bounding box for the given geometry.
  20495. *
  20496. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20497. * @param {Box3} target - The target object that is used to store the method's result.
  20498. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20499. */
  20500. getBoundingBoxAt( geometryId, target ) {
  20501. if ( geometryId >= this._geometryCount ) {
  20502. return null;
  20503. }
  20504. // compute bounding box
  20505. const geometry = this.geometry;
  20506. const geometryInfo = this._geometryInfo[ geometryId ];
  20507. if ( geometryInfo.boundingBox === null ) {
  20508. const box = new Box3();
  20509. const index = geometry.index;
  20510. const position = geometry.attributes.position;
  20511. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20512. let iv = i;
  20513. if ( index ) {
  20514. iv = index.getX( iv );
  20515. }
  20516. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20517. }
  20518. geometryInfo.boundingBox = box;
  20519. }
  20520. target.copy( geometryInfo.boundingBox );
  20521. return target;
  20522. }
  20523. /**
  20524. * Returns the bounding sphere for the given geometry.
  20525. *
  20526. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20527. * @param {Sphere} target - The target object that is used to store the method's result.
  20528. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20529. */
  20530. getBoundingSphereAt( geometryId, target ) {
  20531. if ( geometryId >= this._geometryCount ) {
  20532. return null;
  20533. }
  20534. // compute bounding sphere
  20535. const geometry = this.geometry;
  20536. const geometryInfo = this._geometryInfo[ geometryId ];
  20537. if ( geometryInfo.boundingSphere === null ) {
  20538. const sphere = new Sphere();
  20539. this.getBoundingBoxAt( geometryId, _box$1 );
  20540. _box$1.getCenter( sphere.center );
  20541. const index = geometry.index;
  20542. const position = geometry.attributes.position;
  20543. let maxRadiusSq = 0;
  20544. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20545. let iv = i;
  20546. if ( index ) {
  20547. iv = index.getX( iv );
  20548. }
  20549. _vector$5.fromBufferAttribute( position, iv );
  20550. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20551. }
  20552. sphere.radius = Math.sqrt( maxRadiusSq );
  20553. geometryInfo.boundingSphere = sphere;
  20554. }
  20555. target.copy( geometryInfo.boundingSphere );
  20556. return target;
  20557. }
  20558. /**
  20559. * Sets the given local transformation matrix to the defined instance.
  20560. * Negatively scaled matrices are not supported.
  20561. *
  20562. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20563. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20564. * @return {BatchedMesh} A reference to this batched mesh.
  20565. */
  20566. setMatrixAt( instanceId, matrix ) {
  20567. this.validateInstanceId( instanceId );
  20568. const matricesTexture = this._matricesTexture;
  20569. const matricesArray = this._matricesTexture.image.data;
  20570. matrix.toArray( matricesArray, instanceId * 16 );
  20571. matricesTexture.needsUpdate = true;
  20572. return this;
  20573. }
  20574. /**
  20575. * Returns the local transformation matrix of the defined instance.
  20576. *
  20577. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20578. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20579. * @return {Matrix4} The instance's local transformation matrix.
  20580. */
  20581. getMatrixAt( instanceId, matrix ) {
  20582. this.validateInstanceId( instanceId );
  20583. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20584. }
  20585. /**
  20586. * Sets the given color to the defined instance.
  20587. *
  20588. * @param {number} instanceId - The ID of an instance to set the color of.
  20589. * @param {Color} color - The color to set the instance to.
  20590. * @return {BatchedMesh} A reference to this batched mesh.
  20591. */
  20592. setColorAt( instanceId, color ) {
  20593. this.validateInstanceId( instanceId );
  20594. if ( this._colorsTexture === null ) {
  20595. this._initColorsTexture();
  20596. }
  20597. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20598. this._colorsTexture.needsUpdate = true;
  20599. return this;
  20600. }
  20601. /**
  20602. * Returns the color of the defined instance.
  20603. *
  20604. * @param {number} instanceId - The ID of an instance to get the color of.
  20605. * @param {Color} color - The target object that is used to store the method's result.
  20606. * @return {Color} The instance's color.
  20607. */
  20608. getColorAt( instanceId, color ) {
  20609. this.validateInstanceId( instanceId );
  20610. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20611. }
  20612. /**
  20613. * Sets the visibility of the instance.
  20614. *
  20615. * @param {number} instanceId - The id of the instance to set the visibility of.
  20616. * @param {boolean} visible - Whether the instance is visible or not.
  20617. * @return {BatchedMesh} A reference to this batched mesh.
  20618. */
  20619. setVisibleAt( instanceId, visible ) {
  20620. this.validateInstanceId( instanceId );
  20621. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20622. return this;
  20623. }
  20624. this._instanceInfo[ instanceId ].visible = visible;
  20625. this._visibilityChanged = true;
  20626. return this;
  20627. }
  20628. /**
  20629. * Returns the visibility state of the defined instance.
  20630. *
  20631. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20632. * @return {boolean} Whether the instance is visible or not.
  20633. */
  20634. getVisibleAt( instanceId ) {
  20635. this.validateInstanceId( instanceId );
  20636. return this._instanceInfo[ instanceId ].visible;
  20637. }
  20638. /**
  20639. * Sets the geometry ID of the instance at the given index.
  20640. *
  20641. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20642. * @param {number} geometryId - The geometry ID to be use by the instance.
  20643. * @return {BatchedMesh} A reference to this batched mesh.
  20644. */
  20645. setGeometryIdAt( instanceId, geometryId ) {
  20646. this.validateInstanceId( instanceId );
  20647. this.validateGeometryId( geometryId );
  20648. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20649. return this;
  20650. }
  20651. /**
  20652. * Returns the geometry ID of the defined instance.
  20653. *
  20654. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20655. * @return {number} The instance's geometry ID.
  20656. */
  20657. getGeometryIdAt( instanceId ) {
  20658. this.validateInstanceId( instanceId );
  20659. return this._instanceInfo[ instanceId ].geometryIndex;
  20660. }
  20661. /**
  20662. * Get the range representing the subset of triangles related to the attached geometry,
  20663. * indicating the starting offset and count, or `null` if invalid.
  20664. *
  20665. * @param {number} geometryId - The id of the geometry to get the range of.
  20666. * @param {Object} [target] - The target object that is used to store the method's result.
  20667. * @return {{
  20668. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20669. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20670. * start:number,count:number
  20671. * }} The result object with range data.
  20672. */
  20673. getGeometryRangeAt( geometryId, target = {} ) {
  20674. this.validateGeometryId( geometryId );
  20675. const geometryInfo = this._geometryInfo[ geometryId ];
  20676. target.vertexStart = geometryInfo.vertexStart;
  20677. target.vertexCount = geometryInfo.vertexCount;
  20678. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20679. target.indexStart = geometryInfo.indexStart;
  20680. target.indexCount = geometryInfo.indexCount;
  20681. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20682. target.start = geometryInfo.start;
  20683. target.count = geometryInfo.count;
  20684. return target;
  20685. }
  20686. /**
  20687. * Resizes the necessary buffers to support the provided number of instances.
  20688. * If the provided arguments shrink the number of instances but there are not enough
  20689. * unused Ids at the end of the list then an error is thrown.
  20690. *
  20691. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20692. */
  20693. setInstanceCount( maxInstanceCount ) {
  20694. // shrink the available instances as much as possible
  20695. const availableInstanceIds = this._availableInstanceIds;
  20696. const instanceInfo = this._instanceInfo;
  20697. availableInstanceIds.sort( ascIdSort );
  20698. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20699. instanceInfo.pop();
  20700. availableInstanceIds.pop();
  20701. }
  20702. // throw an error if it can't be shrunk to the desired size
  20703. if ( maxInstanceCount < instanceInfo.length ) {
  20704. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20705. }
  20706. // copy the multi draw counts
  20707. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20708. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20709. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20710. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20711. this._multiDrawCounts = multiDrawCounts;
  20712. this._multiDrawStarts = multiDrawStarts;
  20713. this._maxInstanceCount = maxInstanceCount;
  20714. // update texture data for instance sampling
  20715. const indirectTexture = this._indirectTexture;
  20716. const matricesTexture = this._matricesTexture;
  20717. const colorsTexture = this._colorsTexture;
  20718. indirectTexture.dispose();
  20719. this._initIndirectTexture();
  20720. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20721. matricesTexture.dispose();
  20722. this._initMatricesTexture();
  20723. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20724. if ( colorsTexture ) {
  20725. colorsTexture.dispose();
  20726. this._initColorsTexture();
  20727. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20728. }
  20729. }
  20730. /**
  20731. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20732. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20733. * end of the geometry attributes then an error is thrown.
  20734. *
  20735. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20736. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20737. */
  20738. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20739. // Check if we can shrink to the requested vertex attribute size
  20740. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20741. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20742. if ( requiredVertexLength > maxVertexCount ) {
  20743. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20744. }
  20745. // Check if we can shrink to the requested index attribute size
  20746. if ( this.geometry.index ) {
  20747. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20748. if ( requiredIndexLength > maxIndexCount ) {
  20749. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20750. }
  20751. }
  20752. //
  20753. // dispose of the previous geometry
  20754. const oldGeometry = this.geometry;
  20755. oldGeometry.dispose();
  20756. // recreate the geometry needed based on the previous variant
  20757. this._maxVertexCount = maxVertexCount;
  20758. this._maxIndexCount = maxIndexCount;
  20759. if ( this._geometryInitialized ) {
  20760. this._geometryInitialized = false;
  20761. this.geometry = new BufferGeometry();
  20762. this._initializeGeometry( oldGeometry );
  20763. }
  20764. // copy data from the previous geometry
  20765. const geometry = this.geometry;
  20766. if ( oldGeometry.index ) {
  20767. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20768. }
  20769. for ( const key in oldGeometry.attributes ) {
  20770. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20771. }
  20772. }
  20773. raycast( raycaster, intersects ) {
  20774. const instanceInfo = this._instanceInfo;
  20775. const geometryInfoList = this._geometryInfo;
  20776. const matrixWorld = this.matrixWorld;
  20777. const batchGeometry = this.geometry;
  20778. // iterate over each geometry
  20779. _mesh.material = this.material;
  20780. _mesh.geometry.index = batchGeometry.index;
  20781. _mesh.geometry.attributes = batchGeometry.attributes;
  20782. if ( _mesh.geometry.boundingBox === null ) {
  20783. _mesh.geometry.boundingBox = new Box3();
  20784. }
  20785. if ( _mesh.geometry.boundingSphere === null ) {
  20786. _mesh.geometry.boundingSphere = new Sphere();
  20787. }
  20788. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20789. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20790. continue;
  20791. }
  20792. const geometryId = instanceInfo[ i ].geometryIndex;
  20793. const geometryInfo = geometryInfoList[ geometryId ];
  20794. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20795. // get the intersects
  20796. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20797. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20798. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20799. _mesh.raycast( raycaster, _batchIntersects );
  20800. // add batch id to the intersects
  20801. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20802. const intersect = _batchIntersects[ j ];
  20803. intersect.object = this;
  20804. intersect.batchId = i;
  20805. intersects.push( intersect );
  20806. }
  20807. _batchIntersects.length = 0;
  20808. }
  20809. _mesh.material = null;
  20810. _mesh.geometry.index = null;
  20811. _mesh.geometry.attributes = {};
  20812. _mesh.geometry.setDrawRange( 0, Infinity );
  20813. }
  20814. copy( source ) {
  20815. super.copy( source );
  20816. this.geometry = source.geometry.clone();
  20817. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20818. this.sortObjects = source.sortObjects;
  20819. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20820. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20821. this._geometryInfo = source._geometryInfo.map( info => ( {
  20822. ...info,
  20823. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20824. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20825. } ) );
  20826. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20827. this._availableInstanceIds = source._availableInstanceIds.slice();
  20828. this._availableGeometryIds = source._availableGeometryIds.slice();
  20829. this._nextIndexStart = source._nextIndexStart;
  20830. this._nextVertexStart = source._nextVertexStart;
  20831. this._geometryCount = source._geometryCount;
  20832. this._maxInstanceCount = source._maxInstanceCount;
  20833. this._maxVertexCount = source._maxVertexCount;
  20834. this._maxIndexCount = source._maxIndexCount;
  20835. this._geometryInitialized = source._geometryInitialized;
  20836. this._multiDrawCounts = source._multiDrawCounts.slice();
  20837. this._multiDrawStarts = source._multiDrawStarts.slice();
  20838. this._indirectTexture = source._indirectTexture.clone();
  20839. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20840. this._matricesTexture = source._matricesTexture.clone();
  20841. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20842. if ( this._colorsTexture !== null ) {
  20843. this._colorsTexture = source._colorsTexture.clone();
  20844. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20845. }
  20846. return this;
  20847. }
  20848. /**
  20849. * Frees the GPU-related resources allocated by this instance. Call this
  20850. * method whenever this instance is no longer used in your app.
  20851. */
  20852. dispose() {
  20853. // Assuming the geometry is not shared with other meshes
  20854. this.geometry.dispose();
  20855. this._matricesTexture.dispose();
  20856. this._matricesTexture = null;
  20857. this._indirectTexture.dispose();
  20858. this._indirectTexture = null;
  20859. if ( this._colorsTexture !== null ) {
  20860. this._colorsTexture.dispose();
  20861. this._colorsTexture = null;
  20862. }
  20863. }
  20864. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20865. // if visibility has not changed and frustum culling and object sorting is not required
  20866. // then skip iterating over all items
  20867. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20868. return;
  20869. }
  20870. // the indexed version of the multi draw function requires specifying the start
  20871. // offset in bytes.
  20872. const index = geometry.getIndex();
  20873. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20874. const instanceInfo = this._instanceInfo;
  20875. const multiDrawStarts = this._multiDrawStarts;
  20876. const multiDrawCounts = this._multiDrawCounts;
  20877. const geometryInfoList = this._geometryInfo;
  20878. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20879. const indirectTexture = this._indirectTexture;
  20880. const indirectArray = indirectTexture.image.data;
  20881. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20882. // prepare the frustum in the local frame
  20883. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20884. _matrix$1
  20885. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20886. .multiply( this.matrixWorld );
  20887. _frustum.setFromProjectionMatrix(
  20888. _matrix$1,
  20889. camera.coordinateSystem,
  20890. camera.reversedDepth
  20891. );
  20892. }
  20893. let multiDrawCount = 0;
  20894. if ( this.sortObjects ) {
  20895. // get the camera position in the local frame
  20896. _matrix$1.copy( this.matrixWorld ).invert();
  20897. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20898. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20899. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20900. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20901. const geometryId = instanceInfo[ i ].geometryIndex;
  20902. // get the bounds in world space
  20903. this.getMatrixAt( i, _matrix$1 );
  20904. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20905. // determine whether the batched geometry is within the frustum
  20906. let culled = false;
  20907. if ( perObjectFrustumCulled ) {
  20908. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20909. }
  20910. if ( ! culled ) {
  20911. // get the distance from camera used for sorting
  20912. const geometryInfo = geometryInfoList[ geometryId ];
  20913. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20914. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20915. }
  20916. }
  20917. }
  20918. // Sort the draw ranges and prep for rendering
  20919. const list = _renderList.list;
  20920. const customSort = this.customSort;
  20921. if ( customSort === null ) {
  20922. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20923. } else {
  20924. customSort.call( this, list, camera );
  20925. }
  20926. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20927. const item = list[ i ];
  20928. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  20929. multiDrawCounts[ multiDrawCount ] = item.count;
  20930. indirectArray[ multiDrawCount ] = item.index;
  20931. multiDrawCount ++;
  20932. }
  20933. _renderList.reset();
  20934. } else {
  20935. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20936. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20937. const geometryId = instanceInfo[ i ].geometryIndex;
  20938. // determine whether the batched geometry is within the frustum
  20939. let culled = false;
  20940. if ( perObjectFrustumCulled ) {
  20941. // get the bounds in world space
  20942. this.getMatrixAt( i, _matrix$1 );
  20943. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20944. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20945. }
  20946. if ( ! culled ) {
  20947. const geometryInfo = geometryInfoList[ geometryId ];
  20948. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  20949. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  20950. indirectArray[ multiDrawCount ] = i;
  20951. multiDrawCount ++;
  20952. }
  20953. }
  20954. }
  20955. }
  20956. indirectTexture.needsUpdate = true;
  20957. this._multiDrawCount = multiDrawCount;
  20958. this._visibilityChanged = false;
  20959. }
  20960. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20961. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20962. }
  20963. }
  20964. /**
  20965. * A material for rendering line primitives.
  20966. *
  20967. * Materials define the appearance of renderable 3D objects.
  20968. *
  20969. * ```js
  20970. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20971. * ```
  20972. *
  20973. * @augments Material
  20974. */
  20975. class LineBasicMaterial extends Material {
  20976. /**
  20977. * Constructs a new line basic material.
  20978. *
  20979. * @param {Object} [parameters] - An object with one or more properties
  20980. * defining the material's appearance. Any property of the material
  20981. * (including any property from inherited materials) can be passed
  20982. * in here. Color values can be passed any type of value accepted
  20983. * by {@link Color#set}.
  20984. */
  20985. constructor( parameters ) {
  20986. super();
  20987. /**
  20988. * This flag can be used for type testing.
  20989. *
  20990. * @type {boolean}
  20991. * @readonly
  20992. * @default true
  20993. */
  20994. this.isLineBasicMaterial = true;
  20995. this.type = 'LineBasicMaterial';
  20996. /**
  20997. * Color of the material.
  20998. *
  20999. * @type {Color}
  21000. * @default (1,1,1)
  21001. */
  21002. this.color = new Color( 0xffffff );
  21003. /**
  21004. * Sets the color of the lines using data from a texture. The texture map
  21005. * color is modulated by the diffuse `color`.
  21006. *
  21007. * @type {?Texture}
  21008. * @default null
  21009. */
  21010. this.map = null;
  21011. /**
  21012. * Controls line thickness or lines.
  21013. *
  21014. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21015. * ignore this setting and always render line primitives with a
  21016. * width of one pixel.
  21017. *
  21018. * @type {number}
  21019. * @default 1
  21020. */
  21021. this.linewidth = 1;
  21022. /**
  21023. * Defines appearance of line ends.
  21024. *
  21025. * Can only be used with {@link SVGRenderer}.
  21026. *
  21027. * @type {('butt'|'round'|'square')}
  21028. * @default 'round'
  21029. */
  21030. this.linecap = 'round';
  21031. /**
  21032. * Defines appearance of line joints.
  21033. *
  21034. * Can only be used with {@link SVGRenderer}.
  21035. *
  21036. * @type {('round'|'bevel'|'miter')}
  21037. * @default 'round'
  21038. */
  21039. this.linejoin = 'round';
  21040. /**
  21041. * Whether the material is affected by fog or not.
  21042. *
  21043. * @type {boolean}
  21044. * @default true
  21045. */
  21046. this.fog = true;
  21047. this.setValues( parameters );
  21048. }
  21049. copy( source ) {
  21050. super.copy( source );
  21051. this.color.copy( source.color );
  21052. this.map = source.map;
  21053. this.linewidth = source.linewidth;
  21054. this.linecap = source.linecap;
  21055. this.linejoin = source.linejoin;
  21056. this.fog = source.fog;
  21057. return this;
  21058. }
  21059. }
  21060. const _vStart = /*@__PURE__*/ new Vector3();
  21061. const _vEnd = /*@__PURE__*/ new Vector3();
  21062. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21063. const _ray$1 = /*@__PURE__*/ new Ray();
  21064. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21065. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21066. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21067. /**
  21068. * A continuous line. The line are rendered by connecting consecutive
  21069. * vertices with straight lines.
  21070. *
  21071. * ```js
  21072. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21073. *
  21074. * const points = [];
  21075. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21076. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21077. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21078. *
  21079. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21080. *
  21081. * const line = new THREE.Line( geometry, material );
  21082. * scene.add( line );
  21083. * ```
  21084. *
  21085. * @augments Object3D
  21086. */
  21087. class Line extends Object3D {
  21088. /**
  21089. * Constructs a new line.
  21090. *
  21091. * @param {BufferGeometry} [geometry] - The line geometry.
  21092. * @param {Material|Array<Material>} [material] - The line material.
  21093. */
  21094. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21095. super();
  21096. /**
  21097. * This flag can be used for type testing.
  21098. *
  21099. * @type {boolean}
  21100. * @readonly
  21101. * @default true
  21102. */
  21103. this.isLine = true;
  21104. this.type = 'Line';
  21105. /**
  21106. * The line geometry.
  21107. *
  21108. * @type {BufferGeometry}
  21109. */
  21110. this.geometry = geometry;
  21111. /**
  21112. * The line material.
  21113. *
  21114. * @type {Material|Array<Material>}
  21115. * @default LineBasicMaterial
  21116. */
  21117. this.material = material;
  21118. /**
  21119. * A dictionary representing the morph targets in the geometry. The key is the
  21120. * morph targets name, the value its attribute index. This member is `undefined`
  21121. * by default and only set when morph targets are detected in the geometry.
  21122. *
  21123. * @type {Object<String,number>|undefined}
  21124. * @default undefined
  21125. */
  21126. this.morphTargetDictionary = undefined;
  21127. /**
  21128. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21129. * is applied. This member is `undefined` by default and only set when morph targets are
  21130. * detected in the geometry.
  21131. *
  21132. * @type {Array<number>|undefined}
  21133. * @default undefined
  21134. */
  21135. this.morphTargetInfluences = undefined;
  21136. this.updateMorphTargets();
  21137. }
  21138. copy( source, recursive ) {
  21139. super.copy( source, recursive );
  21140. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21141. this.geometry = source.geometry;
  21142. return this;
  21143. }
  21144. /**
  21145. * Computes an array of distance values which are necessary for rendering dashed lines.
  21146. * For each vertex in the geometry, the method calculates the cumulative length from the
  21147. * current point to the very beginning of the line.
  21148. *
  21149. * @return {Line} A reference to this line.
  21150. */
  21151. computeLineDistances() {
  21152. const geometry = this.geometry;
  21153. // we assume non-indexed geometry
  21154. if ( geometry.index === null ) {
  21155. const positionAttribute = geometry.attributes.position;
  21156. const lineDistances = [ 0 ];
  21157. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21158. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21159. _vEnd.fromBufferAttribute( positionAttribute, i );
  21160. lineDistances[ i ] = lineDistances[ i - 1 ];
  21161. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21162. }
  21163. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21164. } else {
  21165. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21166. }
  21167. return this;
  21168. }
  21169. /**
  21170. * Computes intersection points between a casted ray and this line.
  21171. *
  21172. * @param {Raycaster} raycaster - The raycaster.
  21173. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21174. */
  21175. raycast( raycaster, intersects ) {
  21176. const geometry = this.geometry;
  21177. const matrixWorld = this.matrixWorld;
  21178. const threshold = raycaster.params.Line.threshold;
  21179. const drawRange = geometry.drawRange;
  21180. // Checking boundingSphere distance to ray
  21181. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21182. _sphere$1.copy( geometry.boundingSphere );
  21183. _sphere$1.applyMatrix4( matrixWorld );
  21184. _sphere$1.radius += threshold;
  21185. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21186. //
  21187. _inverseMatrix$1.copy( matrixWorld ).invert();
  21188. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21189. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21190. const localThresholdSq = localThreshold * localThreshold;
  21191. const step = this.isLineSegments ? 2 : 1;
  21192. const index = geometry.index;
  21193. const attributes = geometry.attributes;
  21194. const positionAttribute = attributes.position;
  21195. if ( index !== null ) {
  21196. const start = Math.max( 0, drawRange.start );
  21197. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21198. for ( let i = start, l = end - 1; i < l; i += step ) {
  21199. const a = index.getX( i );
  21200. const b = index.getX( i + 1 );
  21201. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21202. if ( intersect ) {
  21203. intersects.push( intersect );
  21204. }
  21205. }
  21206. if ( this.isLineLoop ) {
  21207. const a = index.getX( end - 1 );
  21208. const b = index.getX( start );
  21209. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21210. if ( intersect ) {
  21211. intersects.push( intersect );
  21212. }
  21213. }
  21214. } else {
  21215. const start = Math.max( 0, drawRange.start );
  21216. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21217. for ( let i = start, l = end - 1; i < l; i += step ) {
  21218. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21219. if ( intersect ) {
  21220. intersects.push( intersect );
  21221. }
  21222. }
  21223. if ( this.isLineLoop ) {
  21224. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21225. if ( intersect ) {
  21226. intersects.push( intersect );
  21227. }
  21228. }
  21229. }
  21230. }
  21231. /**
  21232. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21233. * to make sure existing morph targets can influence this 3D object.
  21234. */
  21235. updateMorphTargets() {
  21236. const geometry = this.geometry;
  21237. const morphAttributes = geometry.morphAttributes;
  21238. const keys = Object.keys( morphAttributes );
  21239. if ( keys.length > 0 ) {
  21240. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21241. if ( morphAttribute !== undefined ) {
  21242. this.morphTargetInfluences = [];
  21243. this.morphTargetDictionary = {};
  21244. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21245. const name = morphAttribute[ m ].name || String( m );
  21246. this.morphTargetInfluences.push( 0 );
  21247. this.morphTargetDictionary[ name ] = m;
  21248. }
  21249. }
  21250. }
  21251. }
  21252. }
  21253. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21254. const positionAttribute = object.geometry.attributes.position;
  21255. _vStart.fromBufferAttribute( positionAttribute, a );
  21256. _vEnd.fromBufferAttribute( positionAttribute, b );
  21257. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21258. if ( distSq > thresholdSq ) return;
  21259. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21260. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21261. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21262. return {
  21263. distance: distance,
  21264. // What do we want? intersection point on the ray or on the segment??
  21265. // point: raycaster.ray.at( distance ),
  21266. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21267. index: i,
  21268. face: null,
  21269. faceIndex: null,
  21270. barycoord: null,
  21271. object: object
  21272. };
  21273. }
  21274. const _start = /*@__PURE__*/ new Vector3();
  21275. const _end = /*@__PURE__*/ new Vector3();
  21276. /**
  21277. * A series of lines drawn between pairs of vertices.
  21278. *
  21279. * @augments Line
  21280. */
  21281. class LineSegments extends Line {
  21282. /**
  21283. * Constructs a new line segments.
  21284. *
  21285. * @param {BufferGeometry} [geometry] - The line geometry.
  21286. * @param {Material|Array<Material>} [material] - The line material.
  21287. */
  21288. constructor( geometry, material ) {
  21289. super( geometry, material );
  21290. /**
  21291. * This flag can be used for type testing.
  21292. *
  21293. * @type {boolean}
  21294. * @readonly
  21295. * @default true
  21296. */
  21297. this.isLineSegments = true;
  21298. this.type = 'LineSegments';
  21299. }
  21300. computeLineDistances() {
  21301. const geometry = this.geometry;
  21302. // we assume non-indexed geometry
  21303. if ( geometry.index === null ) {
  21304. const positionAttribute = geometry.attributes.position;
  21305. const lineDistances = [];
  21306. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21307. _start.fromBufferAttribute( positionAttribute, i );
  21308. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21309. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21310. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21311. }
  21312. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21313. } else {
  21314. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21315. }
  21316. return this;
  21317. }
  21318. }
  21319. /**
  21320. * A continuous line. This is nearly the same as {@link Line} the only difference
  21321. * is that the last vertex is connected with the first vertex in order to close
  21322. * the line to form a loop.
  21323. *
  21324. * @augments Line
  21325. */
  21326. class LineLoop extends Line {
  21327. /**
  21328. * Constructs a new line loop.
  21329. *
  21330. * @param {BufferGeometry} [geometry] - The line geometry.
  21331. * @param {Material|Array<Material>} [material] - The line material.
  21332. */
  21333. constructor( geometry, material ) {
  21334. super( geometry, material );
  21335. /**
  21336. * This flag can be used for type testing.
  21337. *
  21338. * @type {boolean}
  21339. * @readonly
  21340. * @default true
  21341. */
  21342. this.isLineLoop = true;
  21343. this.type = 'LineLoop';
  21344. }
  21345. }
  21346. /**
  21347. * A material for rendering point primitives.
  21348. *
  21349. * Materials define the appearance of renderable 3D objects.
  21350. *
  21351. * ```js
  21352. * const vertices = [];
  21353. *
  21354. * for ( let i = 0; i < 10000; i ++ ) {
  21355. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21356. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21357. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21358. *
  21359. * vertices.push( x, y, z );
  21360. * }
  21361. *
  21362. * const geometry = new THREE.BufferGeometry();
  21363. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21364. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21365. * const points = new THREE.Points( geometry, material );
  21366. * scene.add( points );
  21367. * ```
  21368. *
  21369. * @augments Material
  21370. */
  21371. class PointsMaterial extends Material {
  21372. /**
  21373. * Constructs a new points material.
  21374. *
  21375. * @param {Object} [parameters] - An object with one or more properties
  21376. * defining the material's appearance. Any property of the material
  21377. * (including any property from inherited materials) can be passed
  21378. * in here. Color values can be passed any type of value accepted
  21379. * by {@link Color#set}.
  21380. */
  21381. constructor( parameters ) {
  21382. super();
  21383. /**
  21384. * This flag can be used for type testing.
  21385. *
  21386. * @type {boolean}
  21387. * @readonly
  21388. * @default true
  21389. */
  21390. this.isPointsMaterial = true;
  21391. this.type = 'PointsMaterial';
  21392. /**
  21393. * Color of the material.
  21394. *
  21395. * @type {Color}
  21396. * @default (1,1,1)
  21397. */
  21398. this.color = new Color( 0xffffff );
  21399. /**
  21400. * The color map. May optionally include an alpha channel, typically combined
  21401. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21402. * color is modulated by the diffuse `color`.
  21403. *
  21404. * @type {?Texture}
  21405. * @default null
  21406. */
  21407. this.map = null;
  21408. /**
  21409. * The alpha map is a grayscale texture that controls the opacity across the
  21410. * surface (black: fully transparent; white: fully opaque).
  21411. *
  21412. * Only the color of the texture is used, ignoring the alpha channel if one
  21413. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21414. * when sampling this texture due to the extra bit of precision provided for
  21415. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21416. * luminance/alpha textures will also still work as expected.
  21417. *
  21418. * @type {?Texture}
  21419. * @default null
  21420. */
  21421. this.alphaMap = null;
  21422. /**
  21423. * Defines the size of the points in pixels.
  21424. *
  21425. * Might be capped if the value exceeds hardware dependent parameters like [gl.ALIASED_POINT_SIZE_RANGE]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getParamete}.
  21426. *
  21427. * @type {number}
  21428. * @default 1
  21429. */
  21430. this.size = 1;
  21431. /**
  21432. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21433. *
  21434. * @type {boolean}
  21435. * @default true
  21436. */
  21437. this.sizeAttenuation = true;
  21438. /**
  21439. * Whether the material is affected by fog or not.
  21440. *
  21441. * @type {boolean}
  21442. * @default true
  21443. */
  21444. this.fog = true;
  21445. this.setValues( parameters );
  21446. }
  21447. copy( source ) {
  21448. super.copy( source );
  21449. this.color.copy( source.color );
  21450. this.map = source.map;
  21451. this.alphaMap = source.alphaMap;
  21452. this.size = source.size;
  21453. this.sizeAttenuation = source.sizeAttenuation;
  21454. this.fog = source.fog;
  21455. return this;
  21456. }
  21457. }
  21458. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21459. const _ray = /*@__PURE__*/ new Ray();
  21460. const _sphere = /*@__PURE__*/ new Sphere();
  21461. const _position$2 = /*@__PURE__*/ new Vector3();
  21462. /**
  21463. * A class for displaying points or point clouds.
  21464. *
  21465. * @augments Object3D
  21466. */
  21467. class Points extends Object3D {
  21468. /**
  21469. * Constructs a new point cloud.
  21470. *
  21471. * @param {BufferGeometry} [geometry] - The points geometry.
  21472. * @param {Material|Array<Material>} [material] - The points material.
  21473. */
  21474. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21475. super();
  21476. /**
  21477. * This flag can be used for type testing.
  21478. *
  21479. * @type {boolean}
  21480. * @readonly
  21481. * @default true
  21482. */
  21483. this.isPoints = true;
  21484. this.type = 'Points';
  21485. /**
  21486. * The points geometry.
  21487. *
  21488. * @type {BufferGeometry}
  21489. */
  21490. this.geometry = geometry;
  21491. /**
  21492. * The line material.
  21493. *
  21494. * @type {Material|Array<Material>}
  21495. * @default PointsMaterial
  21496. */
  21497. this.material = material;
  21498. /**
  21499. * A dictionary representing the morph targets in the geometry. The key is the
  21500. * morph targets name, the value its attribute index. This member is `undefined`
  21501. * by default and only set when morph targets are detected in the geometry.
  21502. *
  21503. * @type {Object<String,number>|undefined}
  21504. * @default undefined
  21505. */
  21506. this.morphTargetDictionary = undefined;
  21507. /**
  21508. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21509. * is applied. This member is `undefined` by default and only set when morph targets are
  21510. * detected in the geometry.
  21511. *
  21512. * @type {Array<number>|undefined}
  21513. * @default undefined
  21514. */
  21515. this.morphTargetInfluences = undefined;
  21516. this.updateMorphTargets();
  21517. }
  21518. copy( source, recursive ) {
  21519. super.copy( source, recursive );
  21520. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21521. this.geometry = source.geometry;
  21522. return this;
  21523. }
  21524. /**
  21525. * Computes intersection points between a casted ray and this point cloud.
  21526. *
  21527. * @param {Raycaster} raycaster - The raycaster.
  21528. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21529. */
  21530. raycast( raycaster, intersects ) {
  21531. const geometry = this.geometry;
  21532. const matrixWorld = this.matrixWorld;
  21533. const threshold = raycaster.params.Points.threshold;
  21534. const drawRange = geometry.drawRange;
  21535. // Checking boundingSphere distance to ray
  21536. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21537. _sphere.copy( geometry.boundingSphere );
  21538. _sphere.applyMatrix4( matrixWorld );
  21539. _sphere.radius += threshold;
  21540. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21541. //
  21542. _inverseMatrix.copy( matrixWorld ).invert();
  21543. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21544. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21545. const localThresholdSq = localThreshold * localThreshold;
  21546. const index = geometry.index;
  21547. const attributes = geometry.attributes;
  21548. const positionAttribute = attributes.position;
  21549. if ( index !== null ) {
  21550. const start = Math.max( 0, drawRange.start );
  21551. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21552. for ( let i = start, il = end; i < il; i ++ ) {
  21553. const a = index.getX( i );
  21554. _position$2.fromBufferAttribute( positionAttribute, a );
  21555. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21556. }
  21557. } else {
  21558. const start = Math.max( 0, drawRange.start );
  21559. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21560. for ( let i = start, l = end; i < l; i ++ ) {
  21561. _position$2.fromBufferAttribute( positionAttribute, i );
  21562. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21563. }
  21564. }
  21565. }
  21566. /**
  21567. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21568. * to make sure existing morph targets can influence this 3D object.
  21569. */
  21570. updateMorphTargets() {
  21571. const geometry = this.geometry;
  21572. const morphAttributes = geometry.morphAttributes;
  21573. const keys = Object.keys( morphAttributes );
  21574. if ( keys.length > 0 ) {
  21575. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21576. if ( morphAttribute !== undefined ) {
  21577. this.morphTargetInfluences = [];
  21578. this.morphTargetDictionary = {};
  21579. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21580. const name = morphAttribute[ m ].name || String( m );
  21581. this.morphTargetInfluences.push( 0 );
  21582. this.morphTargetDictionary[ name ] = m;
  21583. }
  21584. }
  21585. }
  21586. }
  21587. }
  21588. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21589. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21590. if ( rayPointDistanceSq < localThresholdSq ) {
  21591. const intersectPoint = new Vector3();
  21592. _ray.closestPointToPoint( point, intersectPoint );
  21593. intersectPoint.applyMatrix4( matrixWorld );
  21594. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21595. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21596. intersects.push( {
  21597. distance: distance,
  21598. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21599. point: intersectPoint,
  21600. index: index,
  21601. face: null,
  21602. faceIndex: null,
  21603. barycoord: null,
  21604. object: object
  21605. } );
  21606. }
  21607. }
  21608. /**
  21609. * A texture for use with a video.
  21610. *
  21611. * ```js
  21612. * // assuming you have created a HTML video element with id="video"
  21613. * const video = document.getElementById( 'video' );
  21614. * const texture = new THREE.VideoTexture( video );
  21615. * ```
  21616. *
  21617. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21618. * set to THREE.SRGBColorSpace.
  21619. *
  21620. * Note: After the initial use of a texture, its dimensions, format, and type
  21621. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21622. *
  21623. * @augments Texture
  21624. */
  21625. class VideoTexture extends Texture {
  21626. /**
  21627. * Constructs a new video texture.
  21628. *
  21629. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21630. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21631. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21632. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21633. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21634. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21635. * @param {number} [format=RGBAFormat] - The texture format.
  21636. * @param {number} [type=UnsignedByteType] - The texture type.
  21637. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21638. */
  21639. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21640. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21641. /**
  21642. * This flag can be used for type testing.
  21643. *
  21644. * @type {boolean}
  21645. * @readonly
  21646. * @default true
  21647. */
  21648. this.isVideoTexture = true;
  21649. /**
  21650. * Whether to generate mipmaps (if possible) for a texture.
  21651. *
  21652. * Overwritten and set to `false` by default.
  21653. *
  21654. * @type {boolean}
  21655. * @default false
  21656. */
  21657. this.generateMipmaps = false;
  21658. /**
  21659. * The video frame request callback identifier, which is a positive integer.
  21660. *
  21661. * Value of 0 represents no scheduled rVFC.
  21662. *
  21663. * @private
  21664. * @type {number}
  21665. */
  21666. this._requestVideoFrameCallbackId = 0;
  21667. const scope = this;
  21668. function updateVideo() {
  21669. scope.needsUpdate = true;
  21670. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21671. }
  21672. if ( 'requestVideoFrameCallback' in video ) {
  21673. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21674. }
  21675. }
  21676. clone() {
  21677. return new this.constructor( this.image ).copy( this );
  21678. }
  21679. /**
  21680. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21681. * to `true` every time a new frame is available.
  21682. *
  21683. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21684. */
  21685. update() {
  21686. const video = this.image;
  21687. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21688. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21689. this.needsUpdate = true;
  21690. }
  21691. }
  21692. dispose() {
  21693. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21694. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21695. }
  21696. super.dispose();
  21697. }
  21698. }
  21699. /**
  21700. * This class can be used as an alternative way to define video data. Instead of using
  21701. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21702. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21703. * video frames are decoded with the WebCodecs API.
  21704. *
  21705. * ```js
  21706. * const texture = new THREE.VideoFrameTexture();
  21707. * texture.setFrame( frame );
  21708. * ```
  21709. *
  21710. * @augments VideoTexture
  21711. */
  21712. class VideoFrameTexture extends VideoTexture {
  21713. /**
  21714. * Constructs a new video frame texture.
  21715. *
  21716. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21717. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21718. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21719. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21720. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21721. * @param {number} [format=RGBAFormat] - The texture format.
  21722. * @param {number} [type=UnsignedByteType] - The texture type.
  21723. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21724. */
  21725. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21726. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21727. /**
  21728. * This flag can be used for type testing.
  21729. *
  21730. * @type {boolean}
  21731. * @readonly
  21732. * @default true
  21733. */
  21734. this.isVideoFrameTexture = true;
  21735. }
  21736. /**
  21737. * This method overwritten with an empty implementation since
  21738. * this type of texture is updated via `setFrame()`.
  21739. */
  21740. update() {}
  21741. clone() {
  21742. return new this.constructor().copy( this ); // restoring Texture.clone()
  21743. }
  21744. /**
  21745. * Sets the current frame of the video. This will automatically update the texture
  21746. * so the data can be used for rendering.
  21747. *
  21748. * @param {VideoFrame} frame - The video frame.
  21749. */
  21750. setFrame( frame ) {
  21751. this.image = frame;
  21752. this.needsUpdate = true;
  21753. }
  21754. }
  21755. /**
  21756. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21757. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21758. * as a texture for further usage.
  21759. *
  21760. * ```js
  21761. * const pixelRatio = window.devicePixelRatio;
  21762. * const textureSize = 128 * pixelRatio;
  21763. *
  21764. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21765. *
  21766. * // calculate start position for copying part of the frame data
  21767. * const vector = new Vector2();
  21768. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21769. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21770. *
  21771. * renderer.render( scene, camera );
  21772. *
  21773. * // copy part of the rendered frame into the framebuffer texture
  21774. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21775. * ```
  21776. *
  21777. * @augments Texture
  21778. */
  21779. class FramebufferTexture extends Texture {
  21780. /**
  21781. * Constructs a new framebuffer texture.
  21782. *
  21783. * @param {number} [width] - The width of the texture.
  21784. * @param {number} [height] - The height of the texture.
  21785. */
  21786. constructor( width, height ) {
  21787. super( { width, height } );
  21788. /**
  21789. * This flag can be used for type testing.
  21790. *
  21791. * @type {boolean}
  21792. * @readonly
  21793. * @default true
  21794. */
  21795. this.isFramebufferTexture = true;
  21796. /**
  21797. * How the texture is sampled when a texel covers more than one pixel.
  21798. *
  21799. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21800. *
  21801. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21802. * @default NearestFilter
  21803. */
  21804. this.magFilter = NearestFilter;
  21805. /**
  21806. * How the texture is sampled when a texel covers less than one pixel.
  21807. *
  21808. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21809. *
  21810. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21811. * @default NearestFilter
  21812. */
  21813. this.minFilter = NearestFilter;
  21814. /**
  21815. * Whether to generate mipmaps (if possible) for a texture.
  21816. *
  21817. * Overwritten and set to `false` by default.
  21818. *
  21819. * @type {boolean}
  21820. * @default false
  21821. */
  21822. this.generateMipmaps = false;
  21823. this.needsUpdate = true;
  21824. }
  21825. }
  21826. /**
  21827. * Creates a texture based on data in compressed form.
  21828. *
  21829. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21830. *
  21831. * @augments Texture
  21832. */
  21833. class CompressedTexture extends Texture {
  21834. /**
  21835. * Constructs a new compressed texture.
  21836. *
  21837. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21838. * the data and dimensions.
  21839. * @param {number} width - The width of the texture.
  21840. * @param {number} height - The height of the texture.
  21841. * @param {number} [format=RGBAFormat] - The texture format.
  21842. * @param {number} [type=UnsignedByteType] - The texture type.
  21843. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21844. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21845. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21846. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21847. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21848. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21849. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21850. */
  21851. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21852. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21853. /**
  21854. * This flag can be used for type testing.
  21855. *
  21856. * @type {boolean}
  21857. * @readonly
  21858. * @default true
  21859. */
  21860. this.isCompressedTexture = true;
  21861. /**
  21862. * The image property of a compressed texture just defines its dimensions.
  21863. *
  21864. * @type {{width:number,height:number}}
  21865. */
  21866. this.image = { width: width, height: height };
  21867. /**
  21868. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21869. *
  21870. * @type {Array<Object>}
  21871. */
  21872. this.mipmaps = mipmaps;
  21873. /**
  21874. * If set to `true`, the texture is flipped along the vertical axis when
  21875. * uploaded to the GPU.
  21876. *
  21877. * Overwritten and set to `false` by default since it is not possible to
  21878. * flip compressed textures.
  21879. *
  21880. * @type {boolean}
  21881. * @default false
  21882. * @readonly
  21883. */
  21884. this.flipY = false;
  21885. /**
  21886. * Whether to generate mipmaps (if possible) for a texture.
  21887. *
  21888. * Overwritten and set to `false` by default since it is not
  21889. * possible to generate mipmaps for compressed data. Mipmaps
  21890. * must be embedded in the compressed texture file.
  21891. *
  21892. * @type {boolean}
  21893. * @default false
  21894. * @readonly
  21895. */
  21896. this.generateMipmaps = false;
  21897. }
  21898. }
  21899. /**
  21900. * Creates a texture 2D array based on data in compressed form.
  21901. *
  21902. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21903. *
  21904. * @augments CompressedTexture
  21905. */
  21906. class CompressedArrayTexture extends CompressedTexture {
  21907. /**
  21908. * Constructs a new compressed array texture.
  21909. *
  21910. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21911. * the data and dimensions.
  21912. * @param {number} width - The width of the texture.
  21913. * @param {number} height - The height of the texture.
  21914. * @param {number} depth - The depth of the texture.
  21915. * @param {number} [format=RGBAFormat] - The min filter value.
  21916. * @param {number} [type=UnsignedByteType] - The min filter value.
  21917. */
  21918. constructor( mipmaps, width, height, depth, format, type ) {
  21919. super( mipmaps, width, height, format, type );
  21920. /**
  21921. * This flag can be used for type testing.
  21922. *
  21923. * @type {boolean}
  21924. * @readonly
  21925. * @default true
  21926. */
  21927. this.isCompressedArrayTexture = true;
  21928. /**
  21929. * The image property of a compressed texture just defines its dimensions.
  21930. *
  21931. * @name CompressedArrayTexture#image
  21932. * @type {{width:number,height:number,depth:number}}
  21933. */
  21934. this.image.depth = depth;
  21935. /**
  21936. * This defines how the texture is wrapped in the depth and corresponds to
  21937. * *W* in UVW mapping.
  21938. *
  21939. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21940. * @default ClampToEdgeWrapping
  21941. */
  21942. this.wrapR = ClampToEdgeWrapping;
  21943. /**
  21944. * A set of all layers which need to be updated in the texture.
  21945. *
  21946. * @type {Set<number>}
  21947. */
  21948. this.layerUpdates = new Set();
  21949. }
  21950. /**
  21951. * Describes that a specific layer of the texture needs to be updated.
  21952. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21953. * entire compressed texture array is sent to the GPU. Marking specific
  21954. * layers will only transmit subsets of all mipmaps associated with a
  21955. * specific depth in the array which is often much more performant.
  21956. *
  21957. * @param {number} layerIndex - The layer index that should be updated.
  21958. */
  21959. addLayerUpdate( layerIndex ) {
  21960. this.layerUpdates.add( layerIndex );
  21961. }
  21962. /**
  21963. * Resets the layer updates registry.
  21964. */
  21965. clearLayerUpdates() {
  21966. this.layerUpdates.clear();
  21967. }
  21968. }
  21969. /**
  21970. * Creates a cube texture based on data in compressed form.
  21971. *
  21972. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21973. *
  21974. * @augments CompressedTexture
  21975. */
  21976. class CompressedCubeTexture extends CompressedTexture {
  21977. /**
  21978. * Constructs a new compressed texture.
  21979. *
  21980. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21981. * @param {number} [format=RGBAFormat] - The texture format.
  21982. * @param {number} [type=UnsignedByteType] - The texture type.
  21983. */
  21984. constructor( images, format, type ) {
  21985. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21986. /**
  21987. * This flag can be used for type testing.
  21988. *
  21989. * @type {boolean}
  21990. * @readonly
  21991. * @default true
  21992. */
  21993. this.isCompressedCubeTexture = true;
  21994. /**
  21995. * This flag can be used for type testing.
  21996. *
  21997. * @type {boolean}
  21998. * @readonly
  21999. * @default true
  22000. */
  22001. this.isCubeTexture = true;
  22002. this.image = images;
  22003. }
  22004. }
  22005. /**
  22006. * Creates a texture from a canvas element.
  22007. *
  22008. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22009. * to `true` immediately since a canvas can directly be used for rendering.
  22010. *
  22011. * @augments Texture
  22012. */
  22013. class CanvasTexture extends Texture {
  22014. /**
  22015. * Constructs a new texture.
  22016. *
  22017. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22018. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22019. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22020. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22021. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22022. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22023. * @param {number} [format=RGBAFormat] - The texture format.
  22024. * @param {number} [type=UnsignedByteType] - The texture type.
  22025. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22026. */
  22027. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22028. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22029. /**
  22030. * This flag can be used for type testing.
  22031. *
  22032. * @type {boolean}
  22033. * @readonly
  22034. * @default true
  22035. */
  22036. this.isCanvasTexture = true;
  22037. this.needsUpdate = true;
  22038. }
  22039. }
  22040. /**
  22041. * This class can be used to automatically save the depth information of a
  22042. * rendering into a texture.
  22043. *
  22044. * @augments Texture
  22045. */
  22046. class DepthTexture extends Texture {
  22047. /**
  22048. * Constructs a new depth texture.
  22049. *
  22050. * @param {number} width - The width of the texture.
  22051. * @param {number} height - The height of the texture.
  22052. * @param {number} [type=UnsignedIntType] - The texture type.
  22053. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22054. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22055. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22056. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22057. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22058. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22059. * @param {number} [format=DepthFormat] - The texture format.
  22060. * @param {number} [depth=1] - The depth of the texture.
  22061. */
  22062. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22063. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22064. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22065. }
  22066. const image = { width: width, height: height, depth: depth };
  22067. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22068. /**
  22069. * This flag can be used for type testing.
  22070. *
  22071. * @type {boolean}
  22072. * @readonly
  22073. * @default true
  22074. */
  22075. this.isDepthTexture = true;
  22076. /**
  22077. * If set to `true`, the texture is flipped along the vertical axis when
  22078. * uploaded to the GPU.
  22079. *
  22080. * Overwritten and set to `false` by default.
  22081. *
  22082. * @type {boolean}
  22083. * @default false
  22084. */
  22085. this.flipY = false;
  22086. /**
  22087. * Whether to generate mipmaps (if possible) for a texture.
  22088. *
  22089. * Overwritten and set to `false` by default.
  22090. *
  22091. * @type {boolean}
  22092. * @default false
  22093. */
  22094. this.generateMipmaps = false;
  22095. /**
  22096. * Code corresponding to the depth compare function.
  22097. *
  22098. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22099. * @default null
  22100. */
  22101. this.compareFunction = null;
  22102. }
  22103. copy( source ) {
  22104. super.copy( source );
  22105. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22106. this.compareFunction = source.compareFunction;
  22107. return this;
  22108. }
  22109. toJSON( meta ) {
  22110. const data = super.toJSON( meta );
  22111. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22112. return data;
  22113. }
  22114. }
  22115. /**
  22116. * Represents a texture created externally with the same renderer context.
  22117. *
  22118. * This may be a texture from a protected media stream, device camera feed,
  22119. * or other data feeds like a depth sensor.
  22120. *
  22121. * Note that this class is only supported in {@link WebGLRenderer}, and in
  22122. * the {@link WebGPURenderer} WebGPU backend.
  22123. *
  22124. * @augments Texture
  22125. */
  22126. class ExternalTexture extends Texture {
  22127. /**
  22128. * Creates a new raw texture.
  22129. *
  22130. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  22131. */
  22132. constructor( sourceTexture = null ) {
  22133. super();
  22134. /**
  22135. * The external source texture.
  22136. *
  22137. * @type {?(WebGLTexture|GPUTexture)}
  22138. * @default null
  22139. */
  22140. this.sourceTexture = sourceTexture;
  22141. /**
  22142. * This flag can be used for type testing.
  22143. *
  22144. * @type {boolean}
  22145. * @readonly
  22146. * @default true
  22147. */
  22148. this.isExternalTexture = true;
  22149. }
  22150. copy( source ) {
  22151. super.copy( source );
  22152. this.sourceTexture = source.sourceTexture;
  22153. return this;
  22154. }
  22155. }
  22156. /**
  22157. * A geometry class for representing a capsule.
  22158. *
  22159. * ```js
  22160. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22161. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22162. * const capsule = new THREE.Mesh( geometry, material );
  22163. * scene.add( capsule );
  22164. * ```
  22165. *
  22166. * @augments BufferGeometry
  22167. */
  22168. class CapsuleGeometry extends BufferGeometry {
  22169. /**
  22170. * Constructs a new capsule geometry.
  22171. *
  22172. * @param {number} [radius=1] - Radius of the capsule.
  22173. * @param {number} [height=1] - Height of the middle section.
  22174. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22175. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22176. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22177. */
  22178. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22179. super();
  22180. this.type = 'CapsuleGeometry';
  22181. /**
  22182. * Holds the constructor parameters that have been
  22183. * used to generate the geometry. Any modification
  22184. * after instantiation does not change the geometry.
  22185. *
  22186. * @type {Object}
  22187. */
  22188. this.parameters = {
  22189. radius: radius,
  22190. height: height,
  22191. capSegments: capSegments,
  22192. radialSegments: radialSegments,
  22193. heightSegments: heightSegments,
  22194. };
  22195. height = Math.max( 0, height );
  22196. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22197. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22198. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22199. // buffers
  22200. const indices = [];
  22201. const vertices = [];
  22202. const normals = [];
  22203. const uvs = [];
  22204. // helper variables
  22205. const halfHeight = height / 2;
  22206. const capArcLength = ( Math.PI / 2 ) * radius;
  22207. const cylinderPartLength = height;
  22208. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22209. const numVerticalSegments = capSegments * 2 + heightSegments;
  22210. const verticesPerRow = radialSegments + 1;
  22211. const normal = new Vector3();
  22212. const vertex = new Vector3();
  22213. // generate vertices, normals, and uvs
  22214. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22215. let currentArcLength = 0;
  22216. let profileY = 0;
  22217. let profileRadius = 0;
  22218. let normalYComponent = 0;
  22219. if ( iy <= capSegments ) {
  22220. // bottom cap
  22221. const segmentProgress = iy / capSegments;
  22222. const angle = ( segmentProgress * Math.PI ) / 2;
  22223. profileY = - halfHeight - radius * Math.cos( angle );
  22224. profileRadius = radius * Math.sin( angle );
  22225. normalYComponent = - radius * Math.cos( angle );
  22226. currentArcLength = segmentProgress * capArcLength;
  22227. } else if ( iy <= capSegments + heightSegments ) {
  22228. // middle section
  22229. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22230. profileY = - halfHeight + segmentProgress * height;
  22231. profileRadius = radius;
  22232. normalYComponent = 0;
  22233. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22234. } else {
  22235. // top cap
  22236. const segmentProgress =
  22237. ( iy - capSegments - heightSegments ) / capSegments;
  22238. const angle = ( segmentProgress * Math.PI ) / 2;
  22239. profileY = halfHeight + radius * Math.sin( angle );
  22240. profileRadius = radius * Math.cos( angle );
  22241. normalYComponent = radius * Math.sin( angle );
  22242. currentArcLength =
  22243. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22244. }
  22245. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22246. // special case for the poles
  22247. let uOffset = 0;
  22248. if ( iy === 0 ) {
  22249. uOffset = 0.5 / radialSegments;
  22250. } else if ( iy === numVerticalSegments ) {
  22251. uOffset = -0.5 / radialSegments;
  22252. }
  22253. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22254. const u = ix / radialSegments;
  22255. const theta = u * Math.PI * 2;
  22256. const sinTheta = Math.sin( theta );
  22257. const cosTheta = Math.cos( theta );
  22258. // vertex
  22259. vertex.x = - profileRadius * cosTheta;
  22260. vertex.y = profileY;
  22261. vertex.z = profileRadius * sinTheta;
  22262. vertices.push( vertex.x, vertex.y, vertex.z );
  22263. // normal
  22264. normal.set(
  22265. - profileRadius * cosTheta,
  22266. normalYComponent,
  22267. profileRadius * sinTheta
  22268. );
  22269. normal.normalize();
  22270. normals.push( normal.x, normal.y, normal.z );
  22271. // uv
  22272. uvs.push( u + uOffset, v );
  22273. }
  22274. if ( iy > 0 ) {
  22275. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22276. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22277. const i1 = prevIndexRow + ix;
  22278. const i2 = prevIndexRow + ix + 1;
  22279. const i3 = iy * verticesPerRow + ix;
  22280. const i4 = iy * verticesPerRow + ix + 1;
  22281. indices.push( i1, i2, i3 );
  22282. indices.push( i2, i4, i3 );
  22283. }
  22284. }
  22285. }
  22286. // build geometry
  22287. this.setIndex( indices );
  22288. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22289. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22290. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22291. }
  22292. copy( source ) {
  22293. super.copy( source );
  22294. this.parameters = Object.assign( {}, source.parameters );
  22295. return this;
  22296. }
  22297. /**
  22298. * Factory method for creating an instance of this class from the given
  22299. * JSON object.
  22300. *
  22301. * @param {Object} data - A JSON object representing the serialized geometry.
  22302. * @return {CapsuleGeometry} A new instance.
  22303. */
  22304. static fromJSON( data ) {
  22305. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22306. }
  22307. }
  22308. /**
  22309. * A simple shape of Euclidean geometry. It is constructed from a
  22310. * number of triangular segments that are oriented around a central point and
  22311. * extend as far out as a given radius. It is built counter-clockwise from a
  22312. * start angle and a given central angle. It can also be used to create
  22313. * regular polygons, where the number of segments determines the number of
  22314. * sides.
  22315. *
  22316. * ```js
  22317. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22318. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22319. * const circle = new THREE.Mesh( geometry, material );
  22320. * scene.add( circle )
  22321. * ```
  22322. *
  22323. * @augments BufferGeometry
  22324. */
  22325. class CircleGeometry extends BufferGeometry {
  22326. /**
  22327. * Constructs a new circle geometry.
  22328. *
  22329. * @param {number} [radius=1] - Radius of the circle.
  22330. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22331. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22332. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22333. * of the circular sector in radians. The default value results in a complete circle.
  22334. */
  22335. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22336. super();
  22337. this.type = 'CircleGeometry';
  22338. /**
  22339. * Holds the constructor parameters that have been
  22340. * used to generate the geometry. Any modification
  22341. * after instantiation does not change the geometry.
  22342. *
  22343. * @type {Object}
  22344. */
  22345. this.parameters = {
  22346. radius: radius,
  22347. segments: segments,
  22348. thetaStart: thetaStart,
  22349. thetaLength: thetaLength
  22350. };
  22351. segments = Math.max( 3, segments );
  22352. // buffers
  22353. const indices = [];
  22354. const vertices = [];
  22355. const normals = [];
  22356. const uvs = [];
  22357. // helper variables
  22358. const vertex = new Vector3();
  22359. const uv = new Vector2();
  22360. // center point
  22361. vertices.push( 0, 0, 0 );
  22362. normals.push( 0, 0, 1 );
  22363. uvs.push( 0.5, 0.5 );
  22364. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22365. const segment = thetaStart + s / segments * thetaLength;
  22366. // vertex
  22367. vertex.x = radius * Math.cos( segment );
  22368. vertex.y = radius * Math.sin( segment );
  22369. vertices.push( vertex.x, vertex.y, vertex.z );
  22370. // normal
  22371. normals.push( 0, 0, 1 );
  22372. // uvs
  22373. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22374. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22375. uvs.push( uv.x, uv.y );
  22376. }
  22377. // indices
  22378. for ( let i = 1; i <= segments; i ++ ) {
  22379. indices.push( i, i + 1, 0 );
  22380. }
  22381. // build geometry
  22382. this.setIndex( indices );
  22383. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22384. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22385. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22386. }
  22387. copy( source ) {
  22388. super.copy( source );
  22389. this.parameters = Object.assign( {}, source.parameters );
  22390. return this;
  22391. }
  22392. /**
  22393. * Factory method for creating an instance of this class from the given
  22394. * JSON object.
  22395. *
  22396. * @param {Object} data - A JSON object representing the serialized geometry.
  22397. * @return {CircleGeometry} A new instance.
  22398. */
  22399. static fromJSON( data ) {
  22400. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22401. }
  22402. }
  22403. /**
  22404. * A geometry class for representing a cylinder.
  22405. *
  22406. * ```js
  22407. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22408. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22409. * const cylinder = new THREE.Mesh( geometry, material );
  22410. * scene.add( cylinder );
  22411. * ```
  22412. *
  22413. * @augments BufferGeometry
  22414. */
  22415. class CylinderGeometry extends BufferGeometry {
  22416. /**
  22417. * Constructs a new cylinder geometry.
  22418. *
  22419. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22420. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22421. * @param {number} [height=1] - Height of the cylinder.
  22422. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22423. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22424. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22425. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22426. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22427. * The default value results in a complete cylinder.
  22428. */
  22429. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22430. super();
  22431. this.type = 'CylinderGeometry';
  22432. /**
  22433. * Holds the constructor parameters that have been
  22434. * used to generate the geometry. Any modification
  22435. * after instantiation does not change the geometry.
  22436. *
  22437. * @type {Object}
  22438. */
  22439. this.parameters = {
  22440. radiusTop: radiusTop,
  22441. radiusBottom: radiusBottom,
  22442. height: height,
  22443. radialSegments: radialSegments,
  22444. heightSegments: heightSegments,
  22445. openEnded: openEnded,
  22446. thetaStart: thetaStart,
  22447. thetaLength: thetaLength
  22448. };
  22449. const scope = this;
  22450. radialSegments = Math.floor( radialSegments );
  22451. heightSegments = Math.floor( heightSegments );
  22452. // buffers
  22453. const indices = [];
  22454. const vertices = [];
  22455. const normals = [];
  22456. const uvs = [];
  22457. // helper variables
  22458. let index = 0;
  22459. const indexArray = [];
  22460. const halfHeight = height / 2;
  22461. let groupStart = 0;
  22462. // generate geometry
  22463. generateTorso();
  22464. if ( openEnded === false ) {
  22465. if ( radiusTop > 0 ) generateCap( true );
  22466. if ( radiusBottom > 0 ) generateCap( false );
  22467. }
  22468. // build geometry
  22469. this.setIndex( indices );
  22470. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22471. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22472. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22473. function generateTorso() {
  22474. const normal = new Vector3();
  22475. const vertex = new Vector3();
  22476. let groupCount = 0;
  22477. // this will be used to calculate the normal
  22478. const slope = ( radiusBottom - radiusTop ) / height;
  22479. // generate vertices, normals and uvs
  22480. for ( let y = 0; y <= heightSegments; y ++ ) {
  22481. const indexRow = [];
  22482. const v = y / heightSegments;
  22483. // calculate the radius of the current row
  22484. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22485. for ( let x = 0; x <= radialSegments; x ++ ) {
  22486. const u = x / radialSegments;
  22487. const theta = u * thetaLength + thetaStart;
  22488. const sinTheta = Math.sin( theta );
  22489. const cosTheta = Math.cos( theta );
  22490. // vertex
  22491. vertex.x = radius * sinTheta;
  22492. vertex.y = - v * height + halfHeight;
  22493. vertex.z = radius * cosTheta;
  22494. vertices.push( vertex.x, vertex.y, vertex.z );
  22495. // normal
  22496. normal.set( sinTheta, slope, cosTheta ).normalize();
  22497. normals.push( normal.x, normal.y, normal.z );
  22498. // uv
  22499. uvs.push( u, 1 - v );
  22500. // save index of vertex in respective row
  22501. indexRow.push( index ++ );
  22502. }
  22503. // now save vertices of the row in our index array
  22504. indexArray.push( indexRow );
  22505. }
  22506. // generate indices
  22507. for ( let x = 0; x < radialSegments; x ++ ) {
  22508. for ( let y = 0; y < heightSegments; y ++ ) {
  22509. // we use the index array to access the correct indices
  22510. const a = indexArray[ y ][ x ];
  22511. const b = indexArray[ y + 1 ][ x ];
  22512. const c = indexArray[ y + 1 ][ x + 1 ];
  22513. const d = indexArray[ y ][ x + 1 ];
  22514. // faces
  22515. if ( radiusTop > 0 || y !== 0 ) {
  22516. indices.push( a, b, d );
  22517. groupCount += 3;
  22518. }
  22519. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22520. indices.push( b, c, d );
  22521. groupCount += 3;
  22522. }
  22523. }
  22524. }
  22525. // add a group to the geometry. this will ensure multi material support
  22526. scope.addGroup( groupStart, groupCount, 0 );
  22527. // calculate new start value for groups
  22528. groupStart += groupCount;
  22529. }
  22530. function generateCap( top ) {
  22531. // save the index of the first center vertex
  22532. const centerIndexStart = index;
  22533. const uv = new Vector2();
  22534. const vertex = new Vector3();
  22535. let groupCount = 0;
  22536. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22537. const sign = ( top === true ) ? 1 : -1;
  22538. // first we generate the center vertex data of the cap.
  22539. // because the geometry needs one set of uvs per face,
  22540. // we must generate a center vertex per face/segment
  22541. for ( let x = 1; x <= radialSegments; x ++ ) {
  22542. // vertex
  22543. vertices.push( 0, halfHeight * sign, 0 );
  22544. // normal
  22545. normals.push( 0, sign, 0 );
  22546. // uv
  22547. uvs.push( 0.5, 0.5 );
  22548. // increase index
  22549. index ++;
  22550. }
  22551. // save the index of the last center vertex
  22552. const centerIndexEnd = index;
  22553. // now we generate the surrounding vertices, normals and uvs
  22554. for ( let x = 0; x <= radialSegments; x ++ ) {
  22555. const u = x / radialSegments;
  22556. const theta = u * thetaLength + thetaStart;
  22557. const cosTheta = Math.cos( theta );
  22558. const sinTheta = Math.sin( theta );
  22559. // vertex
  22560. vertex.x = radius * sinTheta;
  22561. vertex.y = halfHeight * sign;
  22562. vertex.z = radius * cosTheta;
  22563. vertices.push( vertex.x, vertex.y, vertex.z );
  22564. // normal
  22565. normals.push( 0, sign, 0 );
  22566. // uv
  22567. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22568. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22569. uvs.push( uv.x, uv.y );
  22570. // increase index
  22571. index ++;
  22572. }
  22573. // generate indices
  22574. for ( let x = 0; x < radialSegments; x ++ ) {
  22575. const c = centerIndexStart + x;
  22576. const i = centerIndexEnd + x;
  22577. if ( top === true ) {
  22578. // face top
  22579. indices.push( i, i + 1, c );
  22580. } else {
  22581. // face bottom
  22582. indices.push( i + 1, i, c );
  22583. }
  22584. groupCount += 3;
  22585. }
  22586. // add a group to the geometry. this will ensure multi material support
  22587. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22588. // calculate new start value for groups
  22589. groupStart += groupCount;
  22590. }
  22591. }
  22592. copy( source ) {
  22593. super.copy( source );
  22594. this.parameters = Object.assign( {}, source.parameters );
  22595. return this;
  22596. }
  22597. /**
  22598. * Factory method for creating an instance of this class from the given
  22599. * JSON object.
  22600. *
  22601. * @param {Object} data - A JSON object representing the serialized geometry.
  22602. * @return {CylinderGeometry} A new instance.
  22603. */
  22604. static fromJSON( data ) {
  22605. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22606. }
  22607. }
  22608. /**
  22609. * A geometry class for representing a cone.
  22610. *
  22611. * ```js
  22612. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22613. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22614. * const cone = new THREE.Mesh(geometry, material );
  22615. * scene.add( cone );
  22616. * ```
  22617. *
  22618. * @augments CylinderGeometry
  22619. */
  22620. class ConeGeometry extends CylinderGeometry {
  22621. /**
  22622. * Constructs a new cone geometry.
  22623. *
  22624. * @param {number} [radius=1] - Radius of the cone base.
  22625. * @param {number} [height=1] - Height of the cone.
  22626. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22627. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22628. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22629. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22630. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22631. * The default value results in a complete cone.
  22632. */
  22633. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22634. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22635. this.type = 'ConeGeometry';
  22636. /**
  22637. * Holds the constructor parameters that have been
  22638. * used to generate the geometry. Any modification
  22639. * after instantiation does not change the geometry.
  22640. *
  22641. * @type {Object}
  22642. */
  22643. this.parameters = {
  22644. radius: radius,
  22645. height: height,
  22646. radialSegments: radialSegments,
  22647. heightSegments: heightSegments,
  22648. openEnded: openEnded,
  22649. thetaStart: thetaStart,
  22650. thetaLength: thetaLength
  22651. };
  22652. }
  22653. /**
  22654. * Factory method for creating an instance of this class from the given
  22655. * JSON object.
  22656. *
  22657. * @param {Object} data - A JSON object representing the serialized geometry.
  22658. * @return {ConeGeometry} A new instance.
  22659. */
  22660. static fromJSON( data ) {
  22661. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22662. }
  22663. }
  22664. /**
  22665. * A polyhedron is a solid in three dimensions with flat faces. This class
  22666. * will take an array of vertices, project them onto a sphere, and then
  22667. * divide them up to the desired level of detail.
  22668. *
  22669. * @augments BufferGeometry
  22670. */
  22671. class PolyhedronGeometry extends BufferGeometry {
  22672. /**
  22673. * Constructs a new polyhedron geometry.
  22674. *
  22675. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22676. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22677. * @param {number} [radius=1] - The radius of the shape.
  22678. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22679. */
  22680. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22681. super();
  22682. this.type = 'PolyhedronGeometry';
  22683. /**
  22684. * Holds the constructor parameters that have been
  22685. * used to generate the geometry. Any modification
  22686. * after instantiation does not change the geometry.
  22687. *
  22688. * @type {Object}
  22689. */
  22690. this.parameters = {
  22691. vertices: vertices,
  22692. indices: indices,
  22693. radius: radius,
  22694. detail: detail
  22695. };
  22696. // default buffer data
  22697. const vertexBuffer = [];
  22698. const uvBuffer = [];
  22699. // the subdivision creates the vertex buffer data
  22700. subdivide( detail );
  22701. // all vertices should lie on a conceptual sphere with a given radius
  22702. applyRadius( radius );
  22703. // finally, create the uv data
  22704. generateUVs();
  22705. // build non-indexed geometry
  22706. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22707. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22708. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22709. if ( detail === 0 ) {
  22710. this.computeVertexNormals(); // flat normals
  22711. } else {
  22712. this.normalizeNormals(); // smooth normals
  22713. }
  22714. // helper functions
  22715. function subdivide( detail ) {
  22716. const a = new Vector3();
  22717. const b = new Vector3();
  22718. const c = new Vector3();
  22719. // iterate over all faces and apply a subdivision with the given detail value
  22720. for ( let i = 0; i < indices.length; i += 3 ) {
  22721. // get the vertices of the face
  22722. getVertexByIndex( indices[ i + 0 ], a );
  22723. getVertexByIndex( indices[ i + 1 ], b );
  22724. getVertexByIndex( indices[ i + 2 ], c );
  22725. // perform subdivision
  22726. subdivideFace( a, b, c, detail );
  22727. }
  22728. }
  22729. function subdivideFace( a, b, c, detail ) {
  22730. const cols = detail + 1;
  22731. // we use this multidimensional array as a data structure for creating the subdivision
  22732. const v = [];
  22733. // construct all of the vertices for this subdivision
  22734. for ( let i = 0; i <= cols; i ++ ) {
  22735. v[ i ] = [];
  22736. const aj = a.clone().lerp( c, i / cols );
  22737. const bj = b.clone().lerp( c, i / cols );
  22738. const rows = cols - i;
  22739. for ( let j = 0; j <= rows; j ++ ) {
  22740. if ( j === 0 && i === cols ) {
  22741. v[ i ][ j ] = aj;
  22742. } else {
  22743. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22744. }
  22745. }
  22746. }
  22747. // construct all of the faces
  22748. for ( let i = 0; i < cols; i ++ ) {
  22749. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22750. const k = Math.floor( j / 2 );
  22751. if ( j % 2 === 0 ) {
  22752. pushVertex( v[ i ][ k + 1 ] );
  22753. pushVertex( v[ i + 1 ][ k ] );
  22754. pushVertex( v[ i ][ k ] );
  22755. } else {
  22756. pushVertex( v[ i ][ k + 1 ] );
  22757. pushVertex( v[ i + 1 ][ k + 1 ] );
  22758. pushVertex( v[ i + 1 ][ k ] );
  22759. }
  22760. }
  22761. }
  22762. }
  22763. function applyRadius( radius ) {
  22764. const vertex = new Vector3();
  22765. // iterate over the entire buffer and apply the radius to each vertex
  22766. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22767. vertex.x = vertexBuffer[ i + 0 ];
  22768. vertex.y = vertexBuffer[ i + 1 ];
  22769. vertex.z = vertexBuffer[ i + 2 ];
  22770. vertex.normalize().multiplyScalar( radius );
  22771. vertexBuffer[ i + 0 ] = vertex.x;
  22772. vertexBuffer[ i + 1 ] = vertex.y;
  22773. vertexBuffer[ i + 2 ] = vertex.z;
  22774. }
  22775. }
  22776. function generateUVs() {
  22777. const vertex = new Vector3();
  22778. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22779. vertex.x = vertexBuffer[ i + 0 ];
  22780. vertex.y = vertexBuffer[ i + 1 ];
  22781. vertex.z = vertexBuffer[ i + 2 ];
  22782. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22783. const v = inclination( vertex ) / Math.PI + 0.5;
  22784. uvBuffer.push( u, 1 - v );
  22785. }
  22786. correctUVs();
  22787. correctSeam();
  22788. }
  22789. function correctSeam() {
  22790. // handle case when face straddles the seam, see #3269
  22791. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22792. // uv data of a single face
  22793. const x0 = uvBuffer[ i + 0 ];
  22794. const x1 = uvBuffer[ i + 2 ];
  22795. const x2 = uvBuffer[ i + 4 ];
  22796. const max = Math.max( x0, x1, x2 );
  22797. const min = Math.min( x0, x1, x2 );
  22798. // 0.9 is somewhat arbitrary
  22799. if ( max > 0.9 && min < 0.1 ) {
  22800. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22801. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22802. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22803. }
  22804. }
  22805. }
  22806. function pushVertex( vertex ) {
  22807. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22808. }
  22809. function getVertexByIndex( index, vertex ) {
  22810. const stride = index * 3;
  22811. vertex.x = vertices[ stride + 0 ];
  22812. vertex.y = vertices[ stride + 1 ];
  22813. vertex.z = vertices[ stride + 2 ];
  22814. }
  22815. function correctUVs() {
  22816. const a = new Vector3();
  22817. const b = new Vector3();
  22818. const c = new Vector3();
  22819. const centroid = new Vector3();
  22820. const uvA = new Vector2();
  22821. const uvB = new Vector2();
  22822. const uvC = new Vector2();
  22823. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22824. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22825. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22826. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22827. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22828. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22829. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22830. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22831. const azi = azimuth( centroid );
  22832. correctUV( uvA, j + 0, a, azi );
  22833. correctUV( uvB, j + 2, b, azi );
  22834. correctUV( uvC, j + 4, c, azi );
  22835. }
  22836. }
  22837. function correctUV( uv, stride, vector, azimuth ) {
  22838. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22839. uvBuffer[ stride ] = uv.x - 1;
  22840. }
  22841. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22842. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22843. }
  22844. }
  22845. // Angle around the Y axis, counter-clockwise when looking from above.
  22846. function azimuth( vector ) {
  22847. return Math.atan2( vector.z, - vector.x );
  22848. }
  22849. // Angle above the XZ plane.
  22850. function inclination( vector ) {
  22851. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22852. }
  22853. }
  22854. copy( source ) {
  22855. super.copy( source );
  22856. this.parameters = Object.assign( {}, source.parameters );
  22857. return this;
  22858. }
  22859. /**
  22860. * Factory method for creating an instance of this class from the given
  22861. * JSON object.
  22862. *
  22863. * @param {Object} data - A JSON object representing the serialized geometry.
  22864. * @return {PolyhedronGeometry} A new instance.
  22865. */
  22866. static fromJSON( data ) {
  22867. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22868. }
  22869. }
  22870. /**
  22871. * A geometry class for representing a dodecahedron.
  22872. *
  22873. * ```js
  22874. * const geometry = new THREE.DodecahedronGeometry();
  22875. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22876. * const dodecahedron = new THREE.Mesh( geometry, material );
  22877. * scene.add( dodecahedron );
  22878. * ```
  22879. *
  22880. * @augments PolyhedronGeometry
  22881. */
  22882. class DodecahedronGeometry extends PolyhedronGeometry {
  22883. /**
  22884. * Constructs a new dodecahedron geometry.
  22885. *
  22886. * @param {number} [radius=1] - Radius of the dodecahedron.
  22887. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22888. */
  22889. constructor( radius = 1, detail = 0 ) {
  22890. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22891. const r = 1 / t;
  22892. const vertices = [
  22893. // (±1, ±1, ±1)
  22894. -1, -1, -1, -1, -1, 1,
  22895. -1, 1, -1, -1, 1, 1,
  22896. 1, -1, -1, 1, -1, 1,
  22897. 1, 1, -1, 1, 1, 1,
  22898. // (0, ±1/φ, ±φ)
  22899. 0, - r, - t, 0, - r, t,
  22900. 0, r, - t, 0, r, t,
  22901. // (±1/φ, ±φ, 0)
  22902. - r, - t, 0, - r, t, 0,
  22903. r, - t, 0, r, t, 0,
  22904. // (±φ, 0, ±1/φ)
  22905. - t, 0, - r, t, 0, - r,
  22906. - t, 0, r, t, 0, r
  22907. ];
  22908. const indices = [
  22909. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22910. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22911. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22912. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22913. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22914. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22915. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22916. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22917. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22918. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22919. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22920. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22921. ];
  22922. super( vertices, indices, radius, detail );
  22923. this.type = 'DodecahedronGeometry';
  22924. /**
  22925. * Holds the constructor parameters that have been
  22926. * used to generate the geometry. Any modification
  22927. * after instantiation does not change the geometry.
  22928. *
  22929. * @type {Object}
  22930. */
  22931. this.parameters = {
  22932. radius: radius,
  22933. detail: detail
  22934. };
  22935. }
  22936. /**
  22937. * Factory method for creating an instance of this class from the given
  22938. * JSON object.
  22939. *
  22940. * @param {Object} data - A JSON object representing the serialized geometry.
  22941. * @return {DodecahedronGeometry} A new instance.
  22942. */
  22943. static fromJSON( data ) {
  22944. return new DodecahedronGeometry( data.radius, data.detail );
  22945. }
  22946. }
  22947. const _v0 = /*@__PURE__*/ new Vector3();
  22948. const _v1$1 = /*@__PURE__*/ new Vector3();
  22949. const _normal = /*@__PURE__*/ new Vector3();
  22950. const _triangle = /*@__PURE__*/ new Triangle();
  22951. /**
  22952. * Can be used as a helper object to view the edges of a geometry.
  22953. *
  22954. * ```js
  22955. * const geometry = new THREE.BoxGeometry();
  22956. * const edges = new THREE.EdgesGeometry( geometry );
  22957. * const line = new THREE.LineSegments( edges );
  22958. * scene.add( line );
  22959. * ```
  22960. *
  22961. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22962. *
  22963. * @augments BufferGeometry
  22964. */
  22965. class EdgesGeometry extends BufferGeometry {
  22966. /**
  22967. * Constructs a new edges geometry.
  22968. *
  22969. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22970. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22971. * between the face normals of the adjoining faces exceeds this value.
  22972. */
  22973. constructor( geometry = null, thresholdAngle = 1 ) {
  22974. super();
  22975. this.type = 'EdgesGeometry';
  22976. /**
  22977. * Holds the constructor parameters that have been
  22978. * used to generate the geometry. Any modification
  22979. * after instantiation does not change the geometry.
  22980. *
  22981. * @type {Object}
  22982. */
  22983. this.parameters = {
  22984. geometry: geometry,
  22985. thresholdAngle: thresholdAngle
  22986. };
  22987. if ( geometry !== null ) {
  22988. const precisionPoints = 4;
  22989. const precision = Math.pow( 10, precisionPoints );
  22990. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22991. const indexAttr = geometry.getIndex();
  22992. const positionAttr = geometry.getAttribute( 'position' );
  22993. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22994. const indexArr = [ 0, 0, 0 ];
  22995. const vertKeys = [ 'a', 'b', 'c' ];
  22996. const hashes = new Array( 3 );
  22997. const edgeData = {};
  22998. const vertices = [];
  22999. for ( let i = 0; i < indexCount; i += 3 ) {
  23000. if ( indexAttr ) {
  23001. indexArr[ 0 ] = indexAttr.getX( i );
  23002. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  23003. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  23004. } else {
  23005. indexArr[ 0 ] = i;
  23006. indexArr[ 1 ] = i + 1;
  23007. indexArr[ 2 ] = i + 2;
  23008. }
  23009. const { a, b, c } = _triangle;
  23010. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  23011. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  23012. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  23013. _triangle.getNormal( _normal );
  23014. // create hashes for the edge from the vertices
  23015. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  23016. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  23017. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  23018. // skip degenerate triangles
  23019. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  23020. continue;
  23021. }
  23022. // iterate over every edge
  23023. for ( let j = 0; j < 3; j ++ ) {
  23024. // get the first and next vertex making up the edge
  23025. const jNext = ( j + 1 ) % 3;
  23026. const vecHash0 = hashes[ j ];
  23027. const vecHash1 = hashes[ jNext ];
  23028. const v0 = _triangle[ vertKeys[ j ] ];
  23029. const v1 = _triangle[ vertKeys[ jNext ] ];
  23030. const hash = `${ vecHash0 }_${ vecHash1 }`;
  23031. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  23032. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  23033. // if we found a sibling edge add it into the vertex array if
  23034. // it meets the angle threshold and delete the edge from the map.
  23035. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  23036. vertices.push( v0.x, v0.y, v0.z );
  23037. vertices.push( v1.x, v1.y, v1.z );
  23038. }
  23039. edgeData[ reverseHash ] = null;
  23040. } else if ( ! ( hash in edgeData ) ) {
  23041. // if we've already got an edge here then skip adding a new one
  23042. edgeData[ hash ] = {
  23043. index0: indexArr[ j ],
  23044. index1: indexArr[ jNext ],
  23045. normal: _normal.clone(),
  23046. };
  23047. }
  23048. }
  23049. }
  23050. // iterate over all remaining, unmatched edges and add them to the vertex array
  23051. for ( const key in edgeData ) {
  23052. if ( edgeData[ key ] ) {
  23053. const { index0, index1 } = edgeData[ key ];
  23054. _v0.fromBufferAttribute( positionAttr, index0 );
  23055. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23056. vertices.push( _v0.x, _v0.y, _v0.z );
  23057. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23058. }
  23059. }
  23060. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23061. }
  23062. }
  23063. copy( source ) {
  23064. super.copy( source );
  23065. this.parameters = Object.assign( {}, source.parameters );
  23066. return this;
  23067. }
  23068. }
  23069. /**
  23070. * An abstract base class for creating an analytic curve object that contains methods
  23071. * for interpolation.
  23072. *
  23073. * @abstract
  23074. */
  23075. class Curve {
  23076. /**
  23077. * Constructs a new curve.
  23078. */
  23079. constructor() {
  23080. /**
  23081. * The type property is used for detecting the object type
  23082. * in context of serialization/deserialization.
  23083. *
  23084. * @type {string}
  23085. * @readonly
  23086. */
  23087. this.type = 'Curve';
  23088. /**
  23089. * This value determines the amount of divisions when calculating the
  23090. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23091. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23092. * recommended to increase the value of this property if the curve is very large.
  23093. *
  23094. * @type {number}
  23095. * @default 200
  23096. */
  23097. this.arcLengthDivisions = 200;
  23098. /**
  23099. * Must be set to `true` if the curve parameters have changed.
  23100. *
  23101. * @type {boolean}
  23102. * @default false
  23103. */
  23104. this.needsUpdate = false;
  23105. /**
  23106. * An internal cache that holds precomputed curve length values.
  23107. *
  23108. * @private
  23109. * @type {?Array<number>}
  23110. * @default null
  23111. */
  23112. this.cacheArcLengths = null;
  23113. }
  23114. /**
  23115. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23116. * for the given interpolation factor.
  23117. *
  23118. * @abstract
  23119. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23120. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23121. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23122. */
  23123. getPoint( /* t, optionalTarget */ ) {
  23124. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  23125. }
  23126. /**
  23127. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23128. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23129. * of the curve which equidistant samples.
  23130. *
  23131. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23132. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23133. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23134. */
  23135. getPointAt( u, optionalTarget ) {
  23136. const t = this.getUtoTmapping( u );
  23137. return this.getPoint( t, optionalTarget );
  23138. }
  23139. /**
  23140. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23141. * the curve shape.
  23142. *
  23143. * @param {number} [divisions=5] - The number of divisions.
  23144. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23145. */
  23146. getPoints( divisions = 5 ) {
  23147. const points = [];
  23148. for ( let d = 0; d <= divisions; d ++ ) {
  23149. points.push( this.getPoint( d / divisions ) );
  23150. }
  23151. return points;
  23152. }
  23153. // Get sequence of points using getPointAt( u )
  23154. /**
  23155. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23156. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23157. * curve.
  23158. *
  23159. * @param {number} [divisions=5] - The number of divisions.
  23160. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23161. */
  23162. getSpacedPoints( divisions = 5 ) {
  23163. const points = [];
  23164. for ( let d = 0; d <= divisions; d ++ ) {
  23165. points.push( this.getPointAt( d / divisions ) );
  23166. }
  23167. return points;
  23168. }
  23169. /**
  23170. * Returns the total arc length of the curve.
  23171. *
  23172. * @return {number} The length of the curve.
  23173. */
  23174. getLength() {
  23175. const lengths = this.getLengths();
  23176. return lengths[ lengths.length - 1 ];
  23177. }
  23178. /**
  23179. * Returns an array of cumulative segment lengths of the curve.
  23180. *
  23181. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23182. * @return {Array<number>} An array holding the cumulative segment lengths.
  23183. */
  23184. getLengths( divisions = this.arcLengthDivisions ) {
  23185. if ( this.cacheArcLengths &&
  23186. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23187. ! this.needsUpdate ) {
  23188. return this.cacheArcLengths;
  23189. }
  23190. this.needsUpdate = false;
  23191. const cache = [];
  23192. let current, last = this.getPoint( 0 );
  23193. let sum = 0;
  23194. cache.push( 0 );
  23195. for ( let p = 1; p <= divisions; p ++ ) {
  23196. current = this.getPoint( p / divisions );
  23197. sum += current.distanceTo( last );
  23198. cache.push( sum );
  23199. last = current;
  23200. }
  23201. this.cacheArcLengths = cache;
  23202. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23203. }
  23204. /**
  23205. * Update the cumulative segment distance cache. The method must be called
  23206. * every time curve parameters are changed. If an updated curve is part of a
  23207. * composed curve like {@link CurvePath}, this method must be called on the
  23208. * composed curve, too.
  23209. */
  23210. updateArcLengths() {
  23211. this.needsUpdate = true;
  23212. this.getLengths();
  23213. }
  23214. /**
  23215. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23216. * interpolation factor in the same range that can be ued to sample equidistant points
  23217. * from a curve.
  23218. *
  23219. * @param {number} u - The interpolation factor.
  23220. * @param {?number} distance - An optional distance on the curve.
  23221. * @return {number} The updated interpolation factor.
  23222. */
  23223. getUtoTmapping( u, distance = null ) {
  23224. const arcLengths = this.getLengths();
  23225. let i = 0;
  23226. const il = arcLengths.length;
  23227. let targetArcLength; // The targeted u distance value to get
  23228. if ( distance ) {
  23229. targetArcLength = distance;
  23230. } else {
  23231. targetArcLength = u * arcLengths[ il - 1 ];
  23232. }
  23233. // binary search for the index with largest value smaller than target u distance
  23234. let low = 0, high = il - 1, comparison;
  23235. while ( low <= high ) {
  23236. 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
  23237. comparison = arcLengths[ i ] - targetArcLength;
  23238. if ( comparison < 0 ) {
  23239. low = i + 1;
  23240. } else if ( comparison > 0 ) {
  23241. high = i - 1;
  23242. } else {
  23243. high = i;
  23244. break;
  23245. // DONE
  23246. }
  23247. }
  23248. i = high;
  23249. if ( arcLengths[ i ] === targetArcLength ) {
  23250. return i / ( il - 1 );
  23251. }
  23252. // we could get finer grain at lengths, or use simple interpolation between two points
  23253. const lengthBefore = arcLengths[ i ];
  23254. const lengthAfter = arcLengths[ i + 1 ];
  23255. const segmentLength = lengthAfter - lengthBefore;
  23256. // determine where we are between the 'before' and 'after' points
  23257. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23258. // add that fractional amount to t
  23259. const t = ( i + segmentFraction ) / ( il - 1 );
  23260. return t;
  23261. }
  23262. /**
  23263. * Returns a unit vector tangent for the given interpolation factor.
  23264. * If the derived curve does not implement its tangent derivation,
  23265. * two points a small delta apart will be used to find its gradient
  23266. * which seems to give a reasonable approximation.
  23267. *
  23268. * @param {number} t - The interpolation factor.
  23269. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23270. * @return {(Vector2|Vector3)} The tangent vector.
  23271. */
  23272. getTangent( t, optionalTarget ) {
  23273. const delta = 0.0001;
  23274. let t1 = t - delta;
  23275. let t2 = t + delta;
  23276. // Capping in case of danger
  23277. if ( t1 < 0 ) t1 = 0;
  23278. if ( t2 > 1 ) t2 = 1;
  23279. const pt1 = this.getPoint( t1 );
  23280. const pt2 = this.getPoint( t2 );
  23281. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23282. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23283. return tangent;
  23284. }
  23285. /**
  23286. * Same as {@link Curve#getTangent} but with equidistant samples.
  23287. *
  23288. * @param {number} u - The interpolation factor.
  23289. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23290. * @return {(Vector2|Vector3)} The tangent vector.
  23291. * @see {@link Curve#getPointAt}
  23292. */
  23293. getTangentAt( u, optionalTarget ) {
  23294. const t = this.getUtoTmapping( u );
  23295. return this.getTangent( t, optionalTarget );
  23296. }
  23297. /**
  23298. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23299. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23300. *
  23301. * @param {number} segments - The number of segments.
  23302. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23303. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23304. */
  23305. computeFrenetFrames( segments, closed = false ) {
  23306. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23307. const normal = new Vector3();
  23308. const tangents = [];
  23309. const normals = [];
  23310. const binormals = [];
  23311. const vec = new Vector3();
  23312. const mat = new Matrix4();
  23313. // compute the tangent vectors for each segment on the curve
  23314. for ( let i = 0; i <= segments; i ++ ) {
  23315. const u = i / segments;
  23316. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23317. }
  23318. // select an initial normal vector perpendicular to the first tangent vector,
  23319. // and in the direction of the minimum tangent xyz component
  23320. normals[ 0 ] = new Vector3();
  23321. binormals[ 0 ] = new Vector3();
  23322. let min = Number.MAX_VALUE;
  23323. const tx = Math.abs( tangents[ 0 ].x );
  23324. const ty = Math.abs( tangents[ 0 ].y );
  23325. const tz = Math.abs( tangents[ 0 ].z );
  23326. if ( tx <= min ) {
  23327. min = tx;
  23328. normal.set( 1, 0, 0 );
  23329. }
  23330. if ( ty <= min ) {
  23331. min = ty;
  23332. normal.set( 0, 1, 0 );
  23333. }
  23334. if ( tz <= min ) {
  23335. normal.set( 0, 0, 1 );
  23336. }
  23337. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23338. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23339. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23340. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23341. for ( let i = 1; i <= segments; i ++ ) {
  23342. normals[ i ] = normals[ i - 1 ].clone();
  23343. binormals[ i ] = binormals[ i - 1 ].clone();
  23344. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23345. if ( vec.length() > Number.EPSILON ) {
  23346. vec.normalize();
  23347. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23348. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23349. }
  23350. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23351. }
  23352. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23353. if ( closed === true ) {
  23354. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23355. theta /= segments;
  23356. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23357. theta = - theta;
  23358. }
  23359. for ( let i = 1; i <= segments; i ++ ) {
  23360. // twist a little...
  23361. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23362. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23363. }
  23364. }
  23365. return {
  23366. tangents: tangents,
  23367. normals: normals,
  23368. binormals: binormals
  23369. };
  23370. }
  23371. /**
  23372. * Returns a new curve with copied values from this instance.
  23373. *
  23374. * @return {Curve} A clone of this instance.
  23375. */
  23376. clone() {
  23377. return new this.constructor().copy( this );
  23378. }
  23379. /**
  23380. * Copies the values of the given curve to this instance.
  23381. *
  23382. * @param {Curve} source - The curve to copy.
  23383. * @return {Curve} A reference to this curve.
  23384. */
  23385. copy( source ) {
  23386. this.arcLengthDivisions = source.arcLengthDivisions;
  23387. return this;
  23388. }
  23389. /**
  23390. * Serializes the curve into JSON.
  23391. *
  23392. * @return {Object} A JSON object representing the serialized curve.
  23393. * @see {@link ObjectLoader#parse}
  23394. */
  23395. toJSON() {
  23396. const data = {
  23397. metadata: {
  23398. version: 4.7,
  23399. type: 'Curve',
  23400. generator: 'Curve.toJSON'
  23401. }
  23402. };
  23403. data.arcLengthDivisions = this.arcLengthDivisions;
  23404. data.type = this.type;
  23405. return data;
  23406. }
  23407. /**
  23408. * Deserializes the curve from the given JSON.
  23409. *
  23410. * @param {Object} json - The JSON holding the serialized curve.
  23411. * @return {Curve} A reference to this curve.
  23412. */
  23413. fromJSON( json ) {
  23414. this.arcLengthDivisions = json.arcLengthDivisions;
  23415. return this;
  23416. }
  23417. }
  23418. /**
  23419. * A curve representing an ellipse.
  23420. *
  23421. * ```js
  23422. * const curve = new THREE.EllipseCurve(
  23423. * 0, 0,
  23424. * 10, 10,
  23425. * 0, 2 * Math.PI,
  23426. * false,
  23427. * 0
  23428. * );
  23429. *
  23430. * const points = curve.getPoints( 50 );
  23431. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23432. *
  23433. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23434. *
  23435. * // Create the final object to add to the scene
  23436. * const ellipse = new THREE.Line( geometry, material );
  23437. * ```
  23438. *
  23439. * @augments Curve
  23440. */
  23441. class EllipseCurve extends Curve {
  23442. /**
  23443. * Constructs a new ellipse curve.
  23444. *
  23445. * @param {number} [aX=0] - The X center of the ellipse.
  23446. * @param {number} [aY=0] - The Y center of the ellipse.
  23447. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23448. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23449. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23450. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23451. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23452. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23453. */
  23454. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23455. super();
  23456. /**
  23457. * This flag can be used for type testing.
  23458. *
  23459. * @type {boolean}
  23460. * @readonly
  23461. * @default true
  23462. */
  23463. this.isEllipseCurve = true;
  23464. this.type = 'EllipseCurve';
  23465. /**
  23466. * The X center of the ellipse.
  23467. *
  23468. * @type {number}
  23469. * @default 0
  23470. */
  23471. this.aX = aX;
  23472. /**
  23473. * The Y center of the ellipse.
  23474. *
  23475. * @type {number}
  23476. * @default 0
  23477. */
  23478. this.aY = aY;
  23479. /**
  23480. * The radius of the ellipse in the x direction.
  23481. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23482. *
  23483. * @type {number}
  23484. * @default 1
  23485. */
  23486. this.xRadius = xRadius;
  23487. /**
  23488. * The radius of the ellipse in the y direction.
  23489. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23490. *
  23491. * @type {number}
  23492. * @default 1
  23493. */
  23494. this.yRadius = yRadius;
  23495. /**
  23496. * The start angle of the curve in radians starting from the positive X axis.
  23497. *
  23498. * @type {number}
  23499. * @default 0
  23500. */
  23501. this.aStartAngle = aStartAngle;
  23502. /**
  23503. * The end angle of the curve in radians starting from the positive X axis.
  23504. *
  23505. * @type {number}
  23506. * @default Math.PI*2
  23507. */
  23508. this.aEndAngle = aEndAngle;
  23509. /**
  23510. * Whether the ellipse is drawn clockwise or not.
  23511. *
  23512. * @type {boolean}
  23513. * @default false
  23514. */
  23515. this.aClockwise = aClockwise;
  23516. /**
  23517. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23518. *
  23519. * @type {number}
  23520. * @default 0
  23521. */
  23522. this.aRotation = aRotation;
  23523. }
  23524. /**
  23525. * Returns a point on the curve.
  23526. *
  23527. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23528. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23529. * @return {Vector2} The position on the curve.
  23530. */
  23531. getPoint( t, optionalTarget = new Vector2() ) {
  23532. const point = optionalTarget;
  23533. const twoPi = Math.PI * 2;
  23534. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23535. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23536. // ensures that deltaAngle is 0 .. 2 PI
  23537. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23538. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23539. if ( deltaAngle < Number.EPSILON ) {
  23540. if ( samePoints ) {
  23541. deltaAngle = 0;
  23542. } else {
  23543. deltaAngle = twoPi;
  23544. }
  23545. }
  23546. if ( this.aClockwise === true && ! samePoints ) {
  23547. if ( deltaAngle === twoPi ) {
  23548. deltaAngle = - twoPi;
  23549. } else {
  23550. deltaAngle = deltaAngle - twoPi;
  23551. }
  23552. }
  23553. const angle = this.aStartAngle + t * deltaAngle;
  23554. let x = this.aX + this.xRadius * Math.cos( angle );
  23555. let y = this.aY + this.yRadius * Math.sin( angle );
  23556. if ( this.aRotation !== 0 ) {
  23557. const cos = Math.cos( this.aRotation );
  23558. const sin = Math.sin( this.aRotation );
  23559. const tx = x - this.aX;
  23560. const ty = y - this.aY;
  23561. // Rotate the point about the center of the ellipse.
  23562. x = tx * cos - ty * sin + this.aX;
  23563. y = tx * sin + ty * cos + this.aY;
  23564. }
  23565. return point.set( x, y );
  23566. }
  23567. copy( source ) {
  23568. super.copy( source );
  23569. this.aX = source.aX;
  23570. this.aY = source.aY;
  23571. this.xRadius = source.xRadius;
  23572. this.yRadius = source.yRadius;
  23573. this.aStartAngle = source.aStartAngle;
  23574. this.aEndAngle = source.aEndAngle;
  23575. this.aClockwise = source.aClockwise;
  23576. this.aRotation = source.aRotation;
  23577. return this;
  23578. }
  23579. toJSON() {
  23580. const data = super.toJSON();
  23581. data.aX = this.aX;
  23582. data.aY = this.aY;
  23583. data.xRadius = this.xRadius;
  23584. data.yRadius = this.yRadius;
  23585. data.aStartAngle = this.aStartAngle;
  23586. data.aEndAngle = this.aEndAngle;
  23587. data.aClockwise = this.aClockwise;
  23588. data.aRotation = this.aRotation;
  23589. return data;
  23590. }
  23591. fromJSON( json ) {
  23592. super.fromJSON( json );
  23593. this.aX = json.aX;
  23594. this.aY = json.aY;
  23595. this.xRadius = json.xRadius;
  23596. this.yRadius = json.yRadius;
  23597. this.aStartAngle = json.aStartAngle;
  23598. this.aEndAngle = json.aEndAngle;
  23599. this.aClockwise = json.aClockwise;
  23600. this.aRotation = json.aRotation;
  23601. return this;
  23602. }
  23603. }
  23604. /**
  23605. * A curve representing an arc.
  23606. *
  23607. * @augments EllipseCurve
  23608. */
  23609. class ArcCurve extends EllipseCurve {
  23610. /**
  23611. * Constructs a new arc curve.
  23612. *
  23613. * @param {number} [aX=0] - The X center of the ellipse.
  23614. * @param {number} [aY=0] - The Y center of the ellipse.
  23615. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23616. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23617. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23618. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23619. */
  23620. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23621. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23622. /**
  23623. * This flag can be used for type testing.
  23624. *
  23625. * @type {boolean}
  23626. * @readonly
  23627. * @default true
  23628. */
  23629. this.isArcCurve = true;
  23630. this.type = 'ArcCurve';
  23631. }
  23632. }
  23633. function CubicPoly() {
  23634. /**
  23635. * Centripetal CatmullRom Curve - which is useful for avoiding
  23636. * cusps and self-intersections in non-uniform catmull rom curves.
  23637. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23638. *
  23639. * curve.type accepts centripetal(default), chordal and catmullrom
  23640. * curve.tension is used for catmullrom which defaults to 0.5
  23641. */
  23642. /*
  23643. Based on an optimized c++ solution in
  23644. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23645. - http://ideone.com/NoEbVM
  23646. This CubicPoly class could be used for reusing some variables and calculations,
  23647. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23648. which can be placed in CurveUtils.
  23649. */
  23650. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23651. /*
  23652. * Compute coefficients for a cubic polynomial
  23653. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23654. * such that
  23655. * p(0) = x0, p(1) = x1
  23656. * and
  23657. * p'(0) = t0, p'(1) = t1.
  23658. */
  23659. function init( x0, x1, t0, t1 ) {
  23660. c0 = x0;
  23661. c1 = t0;
  23662. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23663. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23664. }
  23665. return {
  23666. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23667. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23668. },
  23669. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23670. // compute tangents when parameterized in [t1,t2]
  23671. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23672. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23673. // rescale tangents for parametrization in [0,1]
  23674. t1 *= dt1;
  23675. t2 *= dt1;
  23676. init( x1, x2, t1, t2 );
  23677. },
  23678. calc: function ( t ) {
  23679. const t2 = t * t;
  23680. const t3 = t2 * t;
  23681. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23682. }
  23683. };
  23684. }
  23685. //
  23686. const tmp = /*@__PURE__*/ new Vector3();
  23687. const px = /*@__PURE__*/ new CubicPoly();
  23688. const py = /*@__PURE__*/ new CubicPoly();
  23689. const pz = /*@__PURE__*/ new CubicPoly();
  23690. /**
  23691. * A curve representing a Catmull-Rom spline.
  23692. *
  23693. * ```js
  23694. * //Create a closed wavey loop
  23695. * const curve = new THREE.CatmullRomCurve3( [
  23696. * new THREE.Vector3( -10, 0, 10 ),
  23697. * new THREE.Vector3( -5, 5, 5 ),
  23698. * new THREE.Vector3( 0, 0, 0 ),
  23699. * new THREE.Vector3( 5, -5, 5 ),
  23700. * new THREE.Vector3( 10, 0, 10 )
  23701. * ] );
  23702. *
  23703. * const points = curve.getPoints( 50 );
  23704. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23705. *
  23706. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23707. *
  23708. * // Create the final object to add to the scene
  23709. * const curveObject = new THREE.Line( geometry, material );
  23710. * ```
  23711. *
  23712. * @augments Curve
  23713. */
  23714. class CatmullRomCurve3 extends Curve {
  23715. /**
  23716. * Constructs a new Catmull-Rom curve.
  23717. *
  23718. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23719. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23720. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23721. * @param {number} [tension=0.5] - Tension of the curve.
  23722. */
  23723. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23724. super();
  23725. /**
  23726. * This flag can be used for type testing.
  23727. *
  23728. * @type {boolean}
  23729. * @readonly
  23730. * @default true
  23731. */
  23732. this.isCatmullRomCurve3 = true;
  23733. this.type = 'CatmullRomCurve3';
  23734. /**
  23735. * An array of 3D points defining the curve.
  23736. *
  23737. * @type {Array<Vector3>}
  23738. */
  23739. this.points = points;
  23740. /**
  23741. * Whether the curve is closed or not.
  23742. *
  23743. * @type {boolean}
  23744. * @default false
  23745. */
  23746. this.closed = closed;
  23747. /**
  23748. * The curve type.
  23749. *
  23750. * @type {('centripetal'|'chordal'|'catmullrom')}
  23751. * @default 'centripetal'
  23752. */
  23753. this.curveType = curveType;
  23754. /**
  23755. * Tension of the curve.
  23756. *
  23757. * @type {number}
  23758. * @default 0.5
  23759. */
  23760. this.tension = tension;
  23761. }
  23762. /**
  23763. * Returns a point on the curve.
  23764. *
  23765. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23766. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23767. * @return {Vector3} The position on the curve.
  23768. */
  23769. getPoint( t, optionalTarget = new Vector3() ) {
  23770. const point = optionalTarget;
  23771. const points = this.points;
  23772. const l = points.length;
  23773. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23774. let intPoint = Math.floor( p );
  23775. let weight = p - intPoint;
  23776. if ( this.closed ) {
  23777. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23778. } else if ( weight === 0 && intPoint === l - 1 ) {
  23779. intPoint = l - 2;
  23780. weight = 1;
  23781. }
  23782. let p0, p3; // 4 points (p1 & p2 defined below)
  23783. if ( this.closed || intPoint > 0 ) {
  23784. p0 = points[ ( intPoint - 1 ) % l ];
  23785. } else {
  23786. // extrapolate first point
  23787. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23788. p0 = tmp;
  23789. }
  23790. const p1 = points[ intPoint % l ];
  23791. const p2 = points[ ( intPoint + 1 ) % l ];
  23792. if ( this.closed || intPoint + 2 < l ) {
  23793. p3 = points[ ( intPoint + 2 ) % l ];
  23794. } else {
  23795. // extrapolate last point
  23796. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23797. p3 = tmp;
  23798. }
  23799. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23800. // init Centripetal / Chordal Catmull-Rom
  23801. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23802. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23803. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23804. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23805. // safety check for repeated points
  23806. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23807. if ( dt0 < 1e-4 ) dt0 = dt1;
  23808. if ( dt2 < 1e-4 ) dt2 = dt1;
  23809. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23810. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23811. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23812. } else if ( this.curveType === 'catmullrom' ) {
  23813. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23814. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23815. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23816. }
  23817. point.set(
  23818. px.calc( weight ),
  23819. py.calc( weight ),
  23820. pz.calc( weight )
  23821. );
  23822. return point;
  23823. }
  23824. copy( source ) {
  23825. super.copy( source );
  23826. this.points = [];
  23827. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23828. const point = source.points[ i ];
  23829. this.points.push( point.clone() );
  23830. }
  23831. this.closed = source.closed;
  23832. this.curveType = source.curveType;
  23833. this.tension = source.tension;
  23834. return this;
  23835. }
  23836. toJSON() {
  23837. const data = super.toJSON();
  23838. data.points = [];
  23839. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23840. const point = this.points[ i ];
  23841. data.points.push( point.toArray() );
  23842. }
  23843. data.closed = this.closed;
  23844. data.curveType = this.curveType;
  23845. data.tension = this.tension;
  23846. return data;
  23847. }
  23848. fromJSON( json ) {
  23849. super.fromJSON( json );
  23850. this.points = [];
  23851. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23852. const point = json.points[ i ];
  23853. this.points.push( new Vector3().fromArray( point ) );
  23854. }
  23855. this.closed = json.closed;
  23856. this.curveType = json.curveType;
  23857. this.tension = json.tension;
  23858. return this;
  23859. }
  23860. }
  23861. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23862. /**
  23863. * Computes a point on a Catmull-Rom spline.
  23864. *
  23865. * @param {number} t - The interpolation factor.
  23866. * @param {number} p0 - The first control point.
  23867. * @param {number} p1 - The second control point.
  23868. * @param {number} p2 - The third control point.
  23869. * @param {number} p3 - The fourth control point.
  23870. * @return {number} The calculated point on a Catmull-Rom spline.
  23871. */
  23872. function CatmullRom( t, p0, p1, p2, p3 ) {
  23873. const v0 = ( p2 - p0 ) * 0.5;
  23874. const v1 = ( p3 - p1 ) * 0.5;
  23875. const t2 = t * t;
  23876. const t3 = t * t2;
  23877. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23878. }
  23879. //
  23880. function QuadraticBezierP0( t, p ) {
  23881. const k = 1 - t;
  23882. return k * k * p;
  23883. }
  23884. function QuadraticBezierP1( t, p ) {
  23885. return 2 * ( 1 - t ) * t * p;
  23886. }
  23887. function QuadraticBezierP2( t, p ) {
  23888. return t * t * p;
  23889. }
  23890. /**
  23891. * Computes a point on a Quadratic Bezier curve.
  23892. *
  23893. * @param {number} t - The interpolation factor.
  23894. * @param {number} p0 - The first control point.
  23895. * @param {number} p1 - The second control point.
  23896. * @param {number} p2 - The third control point.
  23897. * @return {number} The calculated point on a Quadratic Bezier curve.
  23898. */
  23899. function QuadraticBezier( t, p0, p1, p2 ) {
  23900. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23901. QuadraticBezierP2( t, p2 );
  23902. }
  23903. //
  23904. function CubicBezierP0( t, p ) {
  23905. const k = 1 - t;
  23906. return k * k * k * p;
  23907. }
  23908. function CubicBezierP1( t, p ) {
  23909. const k = 1 - t;
  23910. return 3 * k * k * t * p;
  23911. }
  23912. function CubicBezierP2( t, p ) {
  23913. return 3 * ( 1 - t ) * t * t * p;
  23914. }
  23915. function CubicBezierP3( t, p ) {
  23916. return t * t * t * p;
  23917. }
  23918. /**
  23919. * Computes a point on a Cubic Bezier curve.
  23920. *
  23921. * @param {number} t - The interpolation factor.
  23922. * @param {number} p0 - The first control point.
  23923. * @param {number} p1 - The second control point.
  23924. * @param {number} p2 - The third control point.
  23925. * @param {number} p3 - The fourth control point.
  23926. * @return {number} The calculated point on a Cubic Bezier curve.
  23927. */
  23928. function CubicBezier( t, p0, p1, p2, p3 ) {
  23929. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23930. CubicBezierP3( t, p3 );
  23931. }
  23932. /**
  23933. * A curve representing a 2D Cubic Bezier curve.
  23934. *
  23935. * ```js
  23936. * const curve = new THREE.CubicBezierCurve(
  23937. * new THREE.Vector2( - 0, 0 ),
  23938. * new THREE.Vector2( - 5, 15 ),
  23939. * new THREE.Vector2( 20, 15 ),
  23940. * new THREE.Vector2( 10, 0 )
  23941. * );
  23942. *
  23943. * const points = curve.getPoints( 50 );
  23944. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23945. *
  23946. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23947. *
  23948. * // Create the final object to add to the scene
  23949. * const curveObject = new THREE.Line( geometry, material );
  23950. * ```
  23951. *
  23952. * @augments Curve
  23953. */
  23954. class CubicBezierCurve extends Curve {
  23955. /**
  23956. * Constructs a new Cubic Bezier curve.
  23957. *
  23958. * @param {Vector2} [v0] - The start point.
  23959. * @param {Vector2} [v1] - The first control point.
  23960. * @param {Vector2} [v2] - The second control point.
  23961. * @param {Vector2} [v3] - The end point.
  23962. */
  23963. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23964. super();
  23965. /**
  23966. * This flag can be used for type testing.
  23967. *
  23968. * @type {boolean}
  23969. * @readonly
  23970. * @default true
  23971. */
  23972. this.isCubicBezierCurve = true;
  23973. this.type = 'CubicBezierCurve';
  23974. /**
  23975. * The start point.
  23976. *
  23977. * @type {Vector2}
  23978. */
  23979. this.v0 = v0;
  23980. /**
  23981. * The first control point.
  23982. *
  23983. * @type {Vector2}
  23984. */
  23985. this.v1 = v1;
  23986. /**
  23987. * The second control point.
  23988. *
  23989. * @type {Vector2}
  23990. */
  23991. this.v2 = v2;
  23992. /**
  23993. * The end point.
  23994. *
  23995. * @type {Vector2}
  23996. */
  23997. this.v3 = v3;
  23998. }
  23999. /**
  24000. * Returns a point on the curve.
  24001. *
  24002. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24003. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24004. * @return {Vector2} The position on the curve.
  24005. */
  24006. getPoint( t, optionalTarget = new Vector2() ) {
  24007. const point = optionalTarget;
  24008. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24009. point.set(
  24010. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24011. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24012. );
  24013. return point;
  24014. }
  24015. copy( source ) {
  24016. super.copy( source );
  24017. this.v0.copy( source.v0 );
  24018. this.v1.copy( source.v1 );
  24019. this.v2.copy( source.v2 );
  24020. this.v3.copy( source.v3 );
  24021. return this;
  24022. }
  24023. toJSON() {
  24024. const data = super.toJSON();
  24025. data.v0 = this.v0.toArray();
  24026. data.v1 = this.v1.toArray();
  24027. data.v2 = this.v2.toArray();
  24028. data.v3 = this.v3.toArray();
  24029. return data;
  24030. }
  24031. fromJSON( json ) {
  24032. super.fromJSON( json );
  24033. this.v0.fromArray( json.v0 );
  24034. this.v1.fromArray( json.v1 );
  24035. this.v2.fromArray( json.v2 );
  24036. this.v3.fromArray( json.v3 );
  24037. return this;
  24038. }
  24039. }
  24040. /**
  24041. * A curve representing a 3D Cubic Bezier curve.
  24042. *
  24043. * @augments Curve
  24044. */
  24045. class CubicBezierCurve3 extends Curve {
  24046. /**
  24047. * Constructs a new Cubic Bezier curve.
  24048. *
  24049. * @param {Vector3} [v0] - The start point.
  24050. * @param {Vector3} [v1] - The first control point.
  24051. * @param {Vector3} [v2] - The second control point.
  24052. * @param {Vector3} [v3] - The end point.
  24053. */
  24054. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24055. super();
  24056. /**
  24057. * This flag can be used for type testing.
  24058. *
  24059. * @type {boolean}
  24060. * @readonly
  24061. * @default true
  24062. */
  24063. this.isCubicBezierCurve3 = true;
  24064. this.type = 'CubicBezierCurve3';
  24065. /**
  24066. * The start point.
  24067. *
  24068. * @type {Vector3}
  24069. */
  24070. this.v0 = v0;
  24071. /**
  24072. * The first control point.
  24073. *
  24074. * @type {Vector3}
  24075. */
  24076. this.v1 = v1;
  24077. /**
  24078. * The second control point.
  24079. *
  24080. * @type {Vector3}
  24081. */
  24082. this.v2 = v2;
  24083. /**
  24084. * The end point.
  24085. *
  24086. * @type {Vector3}
  24087. */
  24088. this.v3 = v3;
  24089. }
  24090. /**
  24091. * Returns a point on the curve.
  24092. *
  24093. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24094. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24095. * @return {Vector3} The position on the curve.
  24096. */
  24097. getPoint( t, optionalTarget = new Vector3() ) {
  24098. const point = optionalTarget;
  24099. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24100. point.set(
  24101. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24102. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24103. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24104. );
  24105. return point;
  24106. }
  24107. copy( source ) {
  24108. super.copy( source );
  24109. this.v0.copy( source.v0 );
  24110. this.v1.copy( source.v1 );
  24111. this.v2.copy( source.v2 );
  24112. this.v3.copy( source.v3 );
  24113. return this;
  24114. }
  24115. toJSON() {
  24116. const data = super.toJSON();
  24117. data.v0 = this.v0.toArray();
  24118. data.v1 = this.v1.toArray();
  24119. data.v2 = this.v2.toArray();
  24120. data.v3 = this.v3.toArray();
  24121. return data;
  24122. }
  24123. fromJSON( json ) {
  24124. super.fromJSON( json );
  24125. this.v0.fromArray( json.v0 );
  24126. this.v1.fromArray( json.v1 );
  24127. this.v2.fromArray( json.v2 );
  24128. this.v3.fromArray( json.v3 );
  24129. return this;
  24130. }
  24131. }
  24132. /**
  24133. * A curve representing a 2D line segment.
  24134. *
  24135. * @augments Curve
  24136. */
  24137. class LineCurve extends Curve {
  24138. /**
  24139. * Constructs a new line curve.
  24140. *
  24141. * @param {Vector2} [v1] - The start point.
  24142. * @param {Vector2} [v2] - The end point.
  24143. */
  24144. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24145. super();
  24146. /**
  24147. * This flag can be used for type testing.
  24148. *
  24149. * @type {boolean}
  24150. * @readonly
  24151. * @default true
  24152. */
  24153. this.isLineCurve = true;
  24154. this.type = 'LineCurve';
  24155. /**
  24156. * The start point.
  24157. *
  24158. * @type {Vector2}
  24159. */
  24160. this.v1 = v1;
  24161. /**
  24162. * The end point.
  24163. *
  24164. * @type {Vector2}
  24165. */
  24166. this.v2 = v2;
  24167. }
  24168. /**
  24169. * Returns a point on the line.
  24170. *
  24171. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24172. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24173. * @return {Vector2} The position on the line.
  24174. */
  24175. getPoint( t, optionalTarget = new Vector2() ) {
  24176. const point = optionalTarget;
  24177. if ( t === 1 ) {
  24178. point.copy( this.v2 );
  24179. } else {
  24180. point.copy( this.v2 ).sub( this.v1 );
  24181. point.multiplyScalar( t ).add( this.v1 );
  24182. }
  24183. return point;
  24184. }
  24185. // Line curve is linear, so we can overwrite default getPointAt
  24186. getPointAt( u, optionalTarget ) {
  24187. return this.getPoint( u, optionalTarget );
  24188. }
  24189. getTangent( t, optionalTarget = new Vector2() ) {
  24190. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24191. }
  24192. getTangentAt( u, optionalTarget ) {
  24193. return this.getTangent( u, optionalTarget );
  24194. }
  24195. copy( source ) {
  24196. super.copy( source );
  24197. this.v1.copy( source.v1 );
  24198. this.v2.copy( source.v2 );
  24199. return this;
  24200. }
  24201. toJSON() {
  24202. const data = super.toJSON();
  24203. data.v1 = this.v1.toArray();
  24204. data.v2 = this.v2.toArray();
  24205. return data;
  24206. }
  24207. fromJSON( json ) {
  24208. super.fromJSON( json );
  24209. this.v1.fromArray( json.v1 );
  24210. this.v2.fromArray( json.v2 );
  24211. return this;
  24212. }
  24213. }
  24214. /**
  24215. * A curve representing a 3D line segment.
  24216. *
  24217. * @augments Curve
  24218. */
  24219. class LineCurve3 extends Curve {
  24220. /**
  24221. * Constructs a new line curve.
  24222. *
  24223. * @param {Vector3} [v1] - The start point.
  24224. * @param {Vector3} [v2] - The end point.
  24225. */
  24226. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24227. super();
  24228. /**
  24229. * This flag can be used for type testing.
  24230. *
  24231. * @type {boolean}
  24232. * @readonly
  24233. * @default true
  24234. */
  24235. this.isLineCurve3 = true;
  24236. this.type = 'LineCurve3';
  24237. /**
  24238. * The start point.
  24239. *
  24240. * @type {Vector3}
  24241. */
  24242. this.v1 = v1;
  24243. /**
  24244. * The end point.
  24245. *
  24246. * @type {Vector2}
  24247. */
  24248. this.v2 = v2;
  24249. }
  24250. /**
  24251. * Returns a point on the line.
  24252. *
  24253. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24254. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24255. * @return {Vector3} The position on the line.
  24256. */
  24257. getPoint( t, optionalTarget = new Vector3() ) {
  24258. const point = optionalTarget;
  24259. if ( t === 1 ) {
  24260. point.copy( this.v2 );
  24261. } else {
  24262. point.copy( this.v2 ).sub( this.v1 );
  24263. point.multiplyScalar( t ).add( this.v1 );
  24264. }
  24265. return point;
  24266. }
  24267. // Line curve is linear, so we can overwrite default getPointAt
  24268. getPointAt( u, optionalTarget ) {
  24269. return this.getPoint( u, optionalTarget );
  24270. }
  24271. getTangent( t, optionalTarget = new Vector3() ) {
  24272. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24273. }
  24274. getTangentAt( u, optionalTarget ) {
  24275. return this.getTangent( u, optionalTarget );
  24276. }
  24277. copy( source ) {
  24278. super.copy( source );
  24279. this.v1.copy( source.v1 );
  24280. this.v2.copy( source.v2 );
  24281. return this;
  24282. }
  24283. toJSON() {
  24284. const data = super.toJSON();
  24285. data.v1 = this.v1.toArray();
  24286. data.v2 = this.v2.toArray();
  24287. return data;
  24288. }
  24289. fromJSON( json ) {
  24290. super.fromJSON( json );
  24291. this.v1.fromArray( json.v1 );
  24292. this.v2.fromArray( json.v2 );
  24293. return this;
  24294. }
  24295. }
  24296. /**
  24297. * A curve representing a 2D Quadratic Bezier curve.
  24298. *
  24299. * ```js
  24300. * const curve = new THREE.QuadraticBezierCurve(
  24301. * new THREE.Vector2( - 10, 0 ),
  24302. * new THREE.Vector2( 20, 15 ),
  24303. * new THREE.Vector2( 10, 0 )
  24304. * )
  24305. *
  24306. * const points = curve.getPoints( 50 );
  24307. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24308. *
  24309. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24310. *
  24311. * // Create the final object to add to the scene
  24312. * const curveObject = new THREE.Line( geometry, material );
  24313. * ```
  24314. *
  24315. * @augments Curve
  24316. */
  24317. class QuadraticBezierCurve extends Curve {
  24318. /**
  24319. * Constructs a new Quadratic Bezier curve.
  24320. *
  24321. * @param {Vector2} [v0] - The start point.
  24322. * @param {Vector2} [v1] - The control point.
  24323. * @param {Vector2} [v2] - The end point.
  24324. */
  24325. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24326. super();
  24327. /**
  24328. * This flag can be used for type testing.
  24329. *
  24330. * @type {boolean}
  24331. * @readonly
  24332. * @default true
  24333. */
  24334. this.isQuadraticBezierCurve = true;
  24335. this.type = 'QuadraticBezierCurve';
  24336. /**
  24337. * The start point.
  24338. *
  24339. * @type {Vector2}
  24340. */
  24341. this.v0 = v0;
  24342. /**
  24343. * The control point.
  24344. *
  24345. * @type {Vector2}
  24346. */
  24347. this.v1 = v1;
  24348. /**
  24349. * The end point.
  24350. *
  24351. * @type {Vector2}
  24352. */
  24353. this.v2 = v2;
  24354. }
  24355. /**
  24356. * Returns a point on the curve.
  24357. *
  24358. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24359. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24360. * @return {Vector2} The position on the curve.
  24361. */
  24362. getPoint( t, optionalTarget = new Vector2() ) {
  24363. const point = optionalTarget;
  24364. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24365. point.set(
  24366. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24367. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24368. );
  24369. return point;
  24370. }
  24371. copy( source ) {
  24372. super.copy( source );
  24373. this.v0.copy( source.v0 );
  24374. this.v1.copy( source.v1 );
  24375. this.v2.copy( source.v2 );
  24376. return this;
  24377. }
  24378. toJSON() {
  24379. const data = super.toJSON();
  24380. data.v0 = this.v0.toArray();
  24381. data.v1 = this.v1.toArray();
  24382. data.v2 = this.v2.toArray();
  24383. return data;
  24384. }
  24385. fromJSON( json ) {
  24386. super.fromJSON( json );
  24387. this.v0.fromArray( json.v0 );
  24388. this.v1.fromArray( json.v1 );
  24389. this.v2.fromArray( json.v2 );
  24390. return this;
  24391. }
  24392. }
  24393. /**
  24394. * A curve representing a 3D Quadratic Bezier curve.
  24395. *
  24396. * @augments Curve
  24397. */
  24398. class QuadraticBezierCurve3 extends Curve {
  24399. /**
  24400. * Constructs a new Quadratic Bezier curve.
  24401. *
  24402. * @param {Vector3} [v0] - The start point.
  24403. * @param {Vector3} [v1] - The control point.
  24404. * @param {Vector3} [v2] - The end point.
  24405. */
  24406. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24407. super();
  24408. /**
  24409. * This flag can be used for type testing.
  24410. *
  24411. * @type {boolean}
  24412. * @readonly
  24413. * @default true
  24414. */
  24415. this.isQuadraticBezierCurve3 = true;
  24416. this.type = 'QuadraticBezierCurve3';
  24417. /**
  24418. * The start point.
  24419. *
  24420. * @type {Vector3}
  24421. */
  24422. this.v0 = v0;
  24423. /**
  24424. * The control point.
  24425. *
  24426. * @type {Vector3}
  24427. */
  24428. this.v1 = v1;
  24429. /**
  24430. * The end point.
  24431. *
  24432. * @type {Vector3}
  24433. */
  24434. this.v2 = v2;
  24435. }
  24436. /**
  24437. * Returns a point on the curve.
  24438. *
  24439. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24440. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24441. * @return {Vector3} The position on the curve.
  24442. */
  24443. getPoint( t, optionalTarget = new Vector3() ) {
  24444. const point = optionalTarget;
  24445. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24446. point.set(
  24447. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24448. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24449. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24450. );
  24451. return point;
  24452. }
  24453. copy( source ) {
  24454. super.copy( source );
  24455. this.v0.copy( source.v0 );
  24456. this.v1.copy( source.v1 );
  24457. this.v2.copy( source.v2 );
  24458. return this;
  24459. }
  24460. toJSON() {
  24461. const data = super.toJSON();
  24462. data.v0 = this.v0.toArray();
  24463. data.v1 = this.v1.toArray();
  24464. data.v2 = this.v2.toArray();
  24465. return data;
  24466. }
  24467. fromJSON( json ) {
  24468. super.fromJSON( json );
  24469. this.v0.fromArray( json.v0 );
  24470. this.v1.fromArray( json.v1 );
  24471. this.v2.fromArray( json.v2 );
  24472. return this;
  24473. }
  24474. }
  24475. /**
  24476. * A curve representing a 2D spline curve.
  24477. *
  24478. * ```js
  24479. * // Create a sine-like wave
  24480. * const curve = new THREE.SplineCurve( [
  24481. * new THREE.Vector2( -10, 0 ),
  24482. * new THREE.Vector2( -5, 5 ),
  24483. * new THREE.Vector2( 0, 0 ),
  24484. * new THREE.Vector2( 5, -5 ),
  24485. * new THREE.Vector2( 10, 0 )
  24486. * ] );
  24487. *
  24488. * const points = curve.getPoints( 50 );
  24489. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24490. *
  24491. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24492. *
  24493. * // Create the final object to add to the scene
  24494. * const splineObject = new THREE.Line( geometry, material );
  24495. * ```
  24496. *
  24497. * @augments Curve
  24498. */
  24499. class SplineCurve extends Curve {
  24500. /**
  24501. * Constructs a new 2D spline curve.
  24502. *
  24503. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24504. */
  24505. constructor( points = [] ) {
  24506. super();
  24507. /**
  24508. * This flag can be used for type testing.
  24509. *
  24510. * @type {boolean}
  24511. * @readonly
  24512. * @default true
  24513. */
  24514. this.isSplineCurve = true;
  24515. this.type = 'SplineCurve';
  24516. /**
  24517. * An array of 2D points defining the curve.
  24518. *
  24519. * @type {Array<Vector2>}
  24520. */
  24521. this.points = points;
  24522. }
  24523. /**
  24524. * Returns a point on the curve.
  24525. *
  24526. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24527. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24528. * @return {Vector2} The position on the curve.
  24529. */
  24530. getPoint( t, optionalTarget = new Vector2() ) {
  24531. const point = optionalTarget;
  24532. const points = this.points;
  24533. const p = ( points.length - 1 ) * t;
  24534. const intPoint = Math.floor( p );
  24535. const weight = p - intPoint;
  24536. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24537. const p1 = points[ intPoint ];
  24538. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24539. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24540. point.set(
  24541. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24542. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24543. );
  24544. return point;
  24545. }
  24546. copy( source ) {
  24547. super.copy( source );
  24548. this.points = [];
  24549. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24550. const point = source.points[ i ];
  24551. this.points.push( point.clone() );
  24552. }
  24553. return this;
  24554. }
  24555. toJSON() {
  24556. const data = super.toJSON();
  24557. data.points = [];
  24558. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24559. const point = this.points[ i ];
  24560. data.points.push( point.toArray() );
  24561. }
  24562. return data;
  24563. }
  24564. fromJSON( json ) {
  24565. super.fromJSON( json );
  24566. this.points = [];
  24567. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24568. const point = json.points[ i ];
  24569. this.points.push( new Vector2().fromArray( point ) );
  24570. }
  24571. return this;
  24572. }
  24573. }
  24574. var Curves = /*#__PURE__*/Object.freeze({
  24575. __proto__: null,
  24576. ArcCurve: ArcCurve,
  24577. CatmullRomCurve3: CatmullRomCurve3,
  24578. CubicBezierCurve: CubicBezierCurve,
  24579. CubicBezierCurve3: CubicBezierCurve3,
  24580. EllipseCurve: EllipseCurve,
  24581. LineCurve: LineCurve,
  24582. LineCurve3: LineCurve3,
  24583. QuadraticBezierCurve: QuadraticBezierCurve,
  24584. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24585. SplineCurve: SplineCurve
  24586. });
  24587. /**
  24588. * A base class extending {@link Curve}. `CurvePath` is simply an
  24589. * array of connected curves, but retains the API of a curve.
  24590. *
  24591. * @augments Curve
  24592. */
  24593. class CurvePath extends Curve {
  24594. /**
  24595. * Constructs a new curve path.
  24596. */
  24597. constructor() {
  24598. super();
  24599. this.type = 'CurvePath';
  24600. /**
  24601. * An array of curves defining the
  24602. * path.
  24603. *
  24604. * @type {Array<Curve>}
  24605. */
  24606. this.curves = [];
  24607. /**
  24608. * Whether the path should automatically be closed
  24609. * by a line curve.
  24610. *
  24611. * @type {boolean}
  24612. * @default false
  24613. */
  24614. this.autoClose = false;
  24615. }
  24616. /**
  24617. * Adds a curve to this curve path.
  24618. *
  24619. * @param {Curve} curve - The curve to add.
  24620. */
  24621. add( curve ) {
  24622. this.curves.push( curve );
  24623. }
  24624. /**
  24625. * Adds a line curve to close the path.
  24626. *
  24627. * @return {CurvePath} A reference to this curve path.
  24628. */
  24629. closePath() {
  24630. // Add a line curve if start and end of lines are not connected
  24631. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24632. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24633. if ( ! startPoint.equals( endPoint ) ) {
  24634. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24635. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24636. }
  24637. return this;
  24638. }
  24639. /**
  24640. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24641. * for the given interpolation factor.
  24642. *
  24643. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24644. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24645. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24646. */
  24647. getPoint( t, optionalTarget ) {
  24648. // To get accurate point with reference to
  24649. // entire path distance at time t,
  24650. // following has to be done:
  24651. // 1. Length of each sub path have to be known
  24652. // 2. Locate and identify type of curve
  24653. // 3. Get t for the curve
  24654. // 4. Return curve.getPointAt(t')
  24655. const d = t * this.getLength();
  24656. const curveLengths = this.getCurveLengths();
  24657. let i = 0;
  24658. // To think about boundaries points.
  24659. while ( i < curveLengths.length ) {
  24660. if ( curveLengths[ i ] >= d ) {
  24661. const diff = curveLengths[ i ] - d;
  24662. const curve = this.curves[ i ];
  24663. const segmentLength = curve.getLength();
  24664. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24665. return curve.getPointAt( u, optionalTarget );
  24666. }
  24667. i ++;
  24668. }
  24669. return null;
  24670. // loop where sum != 0, sum > d , sum+1 <d
  24671. }
  24672. getLength() {
  24673. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24674. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24675. // getPoint() depends on getLength
  24676. const lens = this.getCurveLengths();
  24677. return lens[ lens.length - 1 ];
  24678. }
  24679. updateArcLengths() {
  24680. // cacheLengths must be recalculated.
  24681. this.needsUpdate = true;
  24682. this.cacheLengths = null;
  24683. this.getCurveLengths();
  24684. }
  24685. /**
  24686. * Returns list of cumulative curve lengths of the defined curves.
  24687. *
  24688. * @return {Array<number>} The curve lengths.
  24689. */
  24690. getCurveLengths() {
  24691. // Compute lengths and cache them
  24692. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24693. // We use cache values if curves and cache array are same length
  24694. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24695. return this.cacheLengths;
  24696. }
  24697. // Get length of sub-curve
  24698. // Push sums into cached array
  24699. const lengths = [];
  24700. let sums = 0;
  24701. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24702. sums += this.curves[ i ].getLength();
  24703. lengths.push( sums );
  24704. }
  24705. this.cacheLengths = lengths;
  24706. return lengths;
  24707. }
  24708. getSpacedPoints( divisions = 40 ) {
  24709. const points = [];
  24710. for ( let i = 0; i <= divisions; i ++ ) {
  24711. points.push( this.getPoint( i / divisions ) );
  24712. }
  24713. if ( this.autoClose ) {
  24714. points.push( points[ 0 ] );
  24715. }
  24716. return points;
  24717. }
  24718. getPoints( divisions = 12 ) {
  24719. const points = [];
  24720. let last;
  24721. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24722. const curve = curves[ i ];
  24723. const resolution = curve.isEllipseCurve ? divisions * 2
  24724. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24725. : curve.isSplineCurve ? divisions * curve.points.length
  24726. : divisions;
  24727. const pts = curve.getPoints( resolution );
  24728. for ( let j = 0; j < pts.length; j ++ ) {
  24729. const point = pts[ j ];
  24730. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24731. points.push( point );
  24732. last = point;
  24733. }
  24734. }
  24735. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24736. points.push( points[ 0 ] );
  24737. }
  24738. return points;
  24739. }
  24740. copy( source ) {
  24741. super.copy( source );
  24742. this.curves = [];
  24743. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24744. const curve = source.curves[ i ];
  24745. this.curves.push( curve.clone() );
  24746. }
  24747. this.autoClose = source.autoClose;
  24748. return this;
  24749. }
  24750. toJSON() {
  24751. const data = super.toJSON();
  24752. data.autoClose = this.autoClose;
  24753. data.curves = [];
  24754. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24755. const curve = this.curves[ i ];
  24756. data.curves.push( curve.toJSON() );
  24757. }
  24758. return data;
  24759. }
  24760. fromJSON( json ) {
  24761. super.fromJSON( json );
  24762. this.autoClose = json.autoClose;
  24763. this.curves = [];
  24764. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24765. const curve = json.curves[ i ];
  24766. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24767. }
  24768. return this;
  24769. }
  24770. }
  24771. /**
  24772. * A 2D path representation. The class provides methods for creating paths
  24773. * and contours of 2D shapes similar to the 2D Canvas API.
  24774. *
  24775. * ```js
  24776. * const path = new THREE.Path();
  24777. *
  24778. * path.lineTo( 0, 0.8 );
  24779. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24780. * path.lineTo( 1, 1 );
  24781. *
  24782. * const points = path.getPoints();
  24783. *
  24784. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24785. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24786. *
  24787. * const line = new THREE.Line( geometry, material );
  24788. * scene.add( line );
  24789. * ```
  24790. *
  24791. * @augments CurvePath
  24792. */
  24793. class Path extends CurvePath {
  24794. /**
  24795. * Constructs a new path.
  24796. *
  24797. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24798. */
  24799. constructor( points ) {
  24800. super();
  24801. this.type = 'Path';
  24802. /**
  24803. * The current offset of the path. Any new curve added will start here.
  24804. *
  24805. * @type {Vector2}
  24806. */
  24807. this.currentPoint = new Vector2();
  24808. if ( points ) {
  24809. this.setFromPoints( points );
  24810. }
  24811. }
  24812. /**
  24813. * Creates a path from the given list of points. The points are added
  24814. * to the path as instances of {@link LineCurve}.
  24815. *
  24816. * @param {Array<Vector2>} points - An array of 2D points.
  24817. * @return {Path} A reference to this path.
  24818. */
  24819. setFromPoints( points ) {
  24820. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24821. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24822. this.lineTo( points[ i ].x, points[ i ].y );
  24823. }
  24824. return this;
  24825. }
  24826. /**
  24827. * Moves {@link Path#currentPoint} to the given point.
  24828. *
  24829. * @param {number} x - The x coordinate.
  24830. * @param {number} y - The y coordinate.
  24831. * @return {Path} A reference to this path.
  24832. */
  24833. moveTo( x, y ) {
  24834. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24835. return this;
  24836. }
  24837. /**
  24838. * Adds an instance of {@link LineCurve} to the path by connecting
  24839. * the current point with the given one.
  24840. *
  24841. * @param {number} x - The x coordinate of the end point.
  24842. * @param {number} y - The y coordinate of the end point.
  24843. * @return {Path} A reference to this path.
  24844. */
  24845. lineTo( x, y ) {
  24846. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24847. this.curves.push( curve );
  24848. this.currentPoint.set( x, y );
  24849. return this;
  24850. }
  24851. /**
  24852. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24853. * the current point with the given one.
  24854. *
  24855. * @param {number} aCPx - The x coordinate of the control point.
  24856. * @param {number} aCPy - The y coordinate of the control point.
  24857. * @param {number} aX - The x coordinate of the end point.
  24858. * @param {number} aY - The y coordinate of the end point.
  24859. * @return {Path} A reference to this path.
  24860. */
  24861. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24862. const curve = new QuadraticBezierCurve(
  24863. this.currentPoint.clone(),
  24864. new Vector2( aCPx, aCPy ),
  24865. new Vector2( aX, aY )
  24866. );
  24867. this.curves.push( curve );
  24868. this.currentPoint.set( aX, aY );
  24869. return this;
  24870. }
  24871. /**
  24872. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24873. * the current point with the given one.
  24874. *
  24875. * @param {number} aCP1x - The x coordinate of the first control point.
  24876. * @param {number} aCP1y - The y coordinate of the first control point.
  24877. * @param {number} aCP2x - The x coordinate of the second control point.
  24878. * @param {number} aCP2y - The y coordinate of the second control point.
  24879. * @param {number} aX - The x coordinate of the end point.
  24880. * @param {number} aY - The y coordinate of the end point.
  24881. * @return {Path} A reference to this path.
  24882. */
  24883. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24884. const curve = new CubicBezierCurve(
  24885. this.currentPoint.clone(),
  24886. new Vector2( aCP1x, aCP1y ),
  24887. new Vector2( aCP2x, aCP2y ),
  24888. new Vector2( aX, aY )
  24889. );
  24890. this.curves.push( curve );
  24891. this.currentPoint.set( aX, aY );
  24892. return this;
  24893. }
  24894. /**
  24895. * Adds an instance of {@link SplineCurve} to the path by connecting
  24896. * the current point with the given list of points.
  24897. *
  24898. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24899. * @return {Path} A reference to this path.
  24900. */
  24901. splineThru( pts ) {
  24902. const npts = [ this.currentPoint.clone() ].concat( pts );
  24903. const curve = new SplineCurve( npts );
  24904. this.curves.push( curve );
  24905. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24906. return this;
  24907. }
  24908. /**
  24909. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24910. * to the current point.
  24911. *
  24912. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24913. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24914. * @param {number} [aRadius=1] - The radius of the arc.
  24915. * @param {number} [aStartAngle=0] - The start angle in radians.
  24916. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24917. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24918. * @return {Path} A reference to this path.
  24919. */
  24920. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24921. const x0 = this.currentPoint.x;
  24922. const y0 = this.currentPoint.y;
  24923. this.absarc( aX + x0, aY + y0, aRadius,
  24924. aStartAngle, aEndAngle, aClockwise );
  24925. return this;
  24926. }
  24927. /**
  24928. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24929. *
  24930. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24931. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24932. * @param {number} [aRadius=1] - The radius of the arc.
  24933. * @param {number} [aStartAngle=0] - The start angle in radians.
  24934. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24935. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24936. * @return {Path} A reference to this path.
  24937. */
  24938. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24939. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24940. return this;
  24941. }
  24942. /**
  24943. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24944. * to the current point
  24945. *
  24946. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24947. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24948. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24949. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24950. * @param {number} [aStartAngle=0] - The start angle in radians.
  24951. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24952. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24953. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24954. * @return {Path} A reference to this path.
  24955. */
  24956. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24957. const x0 = this.currentPoint.x;
  24958. const y0 = this.currentPoint.y;
  24959. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24960. return this;
  24961. }
  24962. /**
  24963. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24964. *
  24965. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24966. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24967. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24968. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24969. * @param {number} [aStartAngle=0] - The start angle in radians.
  24970. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24971. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24972. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24973. * @return {Path} A reference to this path.
  24974. */
  24975. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24976. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24977. if ( this.curves.length > 0 ) {
  24978. // if a previous curve is present, attempt to join
  24979. const firstPoint = curve.getPoint( 0 );
  24980. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24981. this.lineTo( firstPoint.x, firstPoint.y );
  24982. }
  24983. }
  24984. this.curves.push( curve );
  24985. const lastPoint = curve.getPoint( 1 );
  24986. this.currentPoint.copy( lastPoint );
  24987. return this;
  24988. }
  24989. copy( source ) {
  24990. super.copy( source );
  24991. this.currentPoint.copy( source.currentPoint );
  24992. return this;
  24993. }
  24994. toJSON() {
  24995. const data = super.toJSON();
  24996. data.currentPoint = this.currentPoint.toArray();
  24997. return data;
  24998. }
  24999. fromJSON( json ) {
  25000. super.fromJSON( json );
  25001. this.currentPoint.fromArray( json.currentPoint );
  25002. return this;
  25003. }
  25004. }
  25005. /**
  25006. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  25007. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  25008. * points, or to get triangulated faces.
  25009. *
  25010. * ```js
  25011. * const heartShape = new THREE.Shape();
  25012. *
  25013. * heartShape.moveTo( 25, 25 );
  25014. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  25015. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  25016. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  25017. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  25018. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  25019. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  25020. *
  25021. * const extrudeSettings = {
  25022. * depth: 8,
  25023. * bevelEnabled: true,
  25024. * bevelSegments: 2,
  25025. * steps: 2,
  25026. * bevelSize: 1,
  25027. * bevelThickness: 1
  25028. * };
  25029. *
  25030. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  25031. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  25032. * ```
  25033. *
  25034. * @augments Path
  25035. */
  25036. class Shape extends Path {
  25037. /**
  25038. * Constructs a new shape.
  25039. *
  25040. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25041. */
  25042. constructor( points ) {
  25043. super( points );
  25044. /**
  25045. * The UUID of the shape.
  25046. *
  25047. * @type {string}
  25048. * @readonly
  25049. */
  25050. this.uuid = generateUUID();
  25051. this.type = 'Shape';
  25052. /**
  25053. * Defines the holes in the shape. Hole definitions must use the
  25054. * opposite winding order (CW/CCW) than the outer shape.
  25055. *
  25056. * @type {Array<Path>}
  25057. * @readonly
  25058. */
  25059. this.holes = [];
  25060. }
  25061. /**
  25062. * Returns an array representing each contour of the holes
  25063. * as a list of 2D points.
  25064. *
  25065. * @param {number} divisions - The fineness of the result.
  25066. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25067. */
  25068. getPointsHoles( divisions ) {
  25069. const holesPts = [];
  25070. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25071. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25072. }
  25073. return holesPts;
  25074. }
  25075. // get points of shape and holes (keypoints based on segments parameter)
  25076. /**
  25077. * Returns an object that holds contour data for the shape and its holes as
  25078. * arrays of 2D points.
  25079. *
  25080. * @param {number} divisions - The fineness of the result.
  25081. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25082. */
  25083. extractPoints( divisions ) {
  25084. return {
  25085. shape: this.getPoints( divisions ),
  25086. holes: this.getPointsHoles( divisions )
  25087. };
  25088. }
  25089. copy( source ) {
  25090. super.copy( source );
  25091. this.holes = [];
  25092. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25093. const hole = source.holes[ i ];
  25094. this.holes.push( hole.clone() );
  25095. }
  25096. return this;
  25097. }
  25098. toJSON() {
  25099. const data = super.toJSON();
  25100. data.uuid = this.uuid;
  25101. data.holes = [];
  25102. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25103. const hole = this.holes[ i ];
  25104. data.holes.push( hole.toJSON() );
  25105. }
  25106. return data;
  25107. }
  25108. fromJSON( json ) {
  25109. super.fromJSON( json );
  25110. this.uuid = json.uuid;
  25111. this.holes = [];
  25112. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25113. const hole = json.holes[ i ];
  25114. this.holes.push( new Path().fromJSON( hole ) );
  25115. }
  25116. return this;
  25117. }
  25118. }
  25119. /* eslint-disable */
  25120. // copy of mapbox/earcut version 3.0.1
  25121. // https://github.com/mapbox/earcut/tree/v3.0.1
  25122. function earcut(data, holeIndices, dim = 2) {
  25123. const hasHoles = holeIndices && holeIndices.length;
  25124. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25125. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25126. const triangles = [];
  25127. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25128. let minX, minY, invSize;
  25129. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25130. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25131. if (data.length > 80 * dim) {
  25132. minX = Infinity;
  25133. minY = Infinity;
  25134. let maxX = -Infinity;
  25135. let maxY = -Infinity;
  25136. for (let i = dim; i < outerLen; i += dim) {
  25137. const x = data[i];
  25138. const y = data[i + 1];
  25139. if (x < minX) minX = x;
  25140. if (y < minY) minY = y;
  25141. if (x > maxX) maxX = x;
  25142. if (y > maxY) maxY = y;
  25143. }
  25144. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25145. invSize = Math.max(maxX - minX, maxY - minY);
  25146. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25147. }
  25148. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25149. return triangles;
  25150. }
  25151. // create a circular doubly linked list from polygon points in the specified winding order
  25152. function linkedList(data, start, end, dim, clockwise) {
  25153. let last;
  25154. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25155. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25156. } else {
  25157. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25158. }
  25159. if (last && equals(last, last.next)) {
  25160. removeNode(last);
  25161. last = last.next;
  25162. }
  25163. return last;
  25164. }
  25165. // eliminate colinear or duplicate points
  25166. function filterPoints(start, end) {
  25167. if (!start) return start;
  25168. if (!end) end = start;
  25169. let p = start,
  25170. again;
  25171. do {
  25172. again = false;
  25173. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25174. removeNode(p);
  25175. p = end = p.prev;
  25176. if (p === p.next) break;
  25177. again = true;
  25178. } else {
  25179. p = p.next;
  25180. }
  25181. } while (again || p !== end);
  25182. return end;
  25183. }
  25184. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25185. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25186. if (!ear) return;
  25187. // interlink polygon nodes in z-order
  25188. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25189. let stop = ear;
  25190. // iterate through ears, slicing them one by one
  25191. while (ear.prev !== ear.next) {
  25192. const prev = ear.prev;
  25193. const next = ear.next;
  25194. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25195. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25196. removeNode(ear);
  25197. // skipping the next vertex leads to less sliver triangles
  25198. ear = next.next;
  25199. stop = next.next;
  25200. continue;
  25201. }
  25202. ear = next;
  25203. // if we looped through the whole remaining polygon and can't find any more ears
  25204. if (ear === stop) {
  25205. // try filtering points and slicing again
  25206. if (!pass) {
  25207. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25208. // if this didn't work, try curing all small self-intersections locally
  25209. } else if (pass === 1) {
  25210. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25211. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25212. // as a last resort, try splitting the remaining polygon into two
  25213. } else if (pass === 2) {
  25214. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25215. }
  25216. break;
  25217. }
  25218. }
  25219. }
  25220. // check whether a polygon node forms a valid ear with adjacent nodes
  25221. function isEar(ear) {
  25222. const a = ear.prev,
  25223. b = ear,
  25224. c = ear.next;
  25225. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25226. // now make sure we don't have other points inside the potential ear
  25227. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25228. // triangle bbox
  25229. const x0 = Math.min(ax, bx, cx),
  25230. y0 = Math.min(ay, by, cy),
  25231. x1 = Math.max(ax, bx, cx),
  25232. y1 = Math.max(ay, by, cy);
  25233. let p = c.next;
  25234. while (p !== a) {
  25235. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25236. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25237. area(p.prev, p, p.next) >= 0) return false;
  25238. p = p.next;
  25239. }
  25240. return true;
  25241. }
  25242. function isEarHashed(ear, minX, minY, invSize) {
  25243. const a = ear.prev,
  25244. b = ear,
  25245. c = ear.next;
  25246. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25247. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25248. // triangle bbox
  25249. const x0 = Math.min(ax, bx, cx),
  25250. y0 = Math.min(ay, by, cy),
  25251. x1 = Math.max(ax, bx, cx),
  25252. y1 = Math.max(ay, by, cy);
  25253. // z-order range for the current triangle bbox;
  25254. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25255. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25256. let p = ear.prevZ,
  25257. n = ear.nextZ;
  25258. // look for points inside the triangle in both directions
  25259. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25260. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25261. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25262. p = p.prevZ;
  25263. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25264. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25265. n = n.nextZ;
  25266. }
  25267. // look for remaining points in decreasing z-order
  25268. while (p && p.z >= minZ) {
  25269. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25270. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25271. p = p.prevZ;
  25272. }
  25273. // look for remaining points in increasing z-order
  25274. while (n && n.z <= maxZ) {
  25275. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25276. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25277. n = n.nextZ;
  25278. }
  25279. return true;
  25280. }
  25281. // go through all polygon nodes and cure small local self-intersections
  25282. function cureLocalIntersections(start, triangles) {
  25283. let p = start;
  25284. do {
  25285. const a = p.prev,
  25286. b = p.next.next;
  25287. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25288. triangles.push(a.i, p.i, b.i);
  25289. // remove two nodes involved
  25290. removeNode(p);
  25291. removeNode(p.next);
  25292. p = start = b;
  25293. }
  25294. p = p.next;
  25295. } while (p !== start);
  25296. return filterPoints(p);
  25297. }
  25298. // try splitting polygon into two and triangulate them independently
  25299. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25300. // look for a valid diagonal that divides the polygon into two
  25301. let a = start;
  25302. do {
  25303. let b = a.next.next;
  25304. while (b !== a.prev) {
  25305. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25306. // split the polygon in two by the diagonal
  25307. let c = splitPolygon(a, b);
  25308. // filter colinear points around the cuts
  25309. a = filterPoints(a, a.next);
  25310. c = filterPoints(c, c.next);
  25311. // run earcut on each half
  25312. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25313. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25314. return;
  25315. }
  25316. b = b.next;
  25317. }
  25318. a = a.next;
  25319. } while (a !== start);
  25320. }
  25321. // link every hole into the outer loop, producing a single-ring polygon without holes
  25322. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25323. const queue = [];
  25324. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25325. const start = holeIndices[i] * dim;
  25326. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25327. const list = linkedList(data, start, end, dim, false);
  25328. if (list === list.next) list.steiner = true;
  25329. queue.push(getLeftmost(list));
  25330. }
  25331. queue.sort(compareXYSlope);
  25332. // process holes from left to right
  25333. for (let i = 0; i < queue.length; i++) {
  25334. outerNode = eliminateHole(queue[i], outerNode);
  25335. }
  25336. return outerNode;
  25337. }
  25338. function compareXYSlope(a, b) {
  25339. let result = a.x - b.x;
  25340. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25341. // the bridge to the outer shell is always the point that they meet at.
  25342. if (result === 0) {
  25343. result = a.y - b.y;
  25344. if (result === 0) {
  25345. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25346. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25347. result = aSlope - bSlope;
  25348. }
  25349. }
  25350. return result;
  25351. }
  25352. // find a bridge between vertices that connects hole with an outer ring and and link it
  25353. function eliminateHole(hole, outerNode) {
  25354. const bridge = findHoleBridge(hole, outerNode);
  25355. if (!bridge) {
  25356. return outerNode;
  25357. }
  25358. const bridgeReverse = splitPolygon(bridge, hole);
  25359. // filter collinear points around the cuts
  25360. filterPoints(bridgeReverse, bridgeReverse.next);
  25361. return filterPoints(bridge, bridge.next);
  25362. }
  25363. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25364. function findHoleBridge(hole, outerNode) {
  25365. let p = outerNode;
  25366. const hx = hole.x;
  25367. const hy = hole.y;
  25368. let qx = -Infinity;
  25369. let m;
  25370. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25371. // segment's endpoint with lesser x will be potential connection point
  25372. // unless they intersect at a vertex, then choose the vertex
  25373. if (equals(hole, p)) return p;
  25374. do {
  25375. if (equals(hole, p.next)) return p.next;
  25376. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25377. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25378. if (x <= hx && x > qx) {
  25379. qx = x;
  25380. m = p.x < p.next.x ? p : p.next;
  25381. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25382. }
  25383. }
  25384. p = p.next;
  25385. } while (p !== outerNode);
  25386. if (!m) return null;
  25387. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25388. // if there are no points found, we have a valid connection;
  25389. // otherwise choose the point of the minimum angle with the ray as connection point
  25390. const stop = m;
  25391. const mx = m.x;
  25392. const my = m.y;
  25393. let tanMin = Infinity;
  25394. p = m;
  25395. do {
  25396. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25397. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25398. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25399. if (locallyInside(p, hole) &&
  25400. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25401. m = p;
  25402. tanMin = tan;
  25403. }
  25404. }
  25405. p = p.next;
  25406. } while (p !== stop);
  25407. return m;
  25408. }
  25409. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25410. function sectorContainsSector(m, p) {
  25411. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25412. }
  25413. // interlink polygon nodes in z-order
  25414. function indexCurve(start, minX, minY, invSize) {
  25415. let p = start;
  25416. do {
  25417. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25418. p.prevZ = p.prev;
  25419. p.nextZ = p.next;
  25420. p = p.next;
  25421. } while (p !== start);
  25422. p.prevZ.nextZ = null;
  25423. p.prevZ = null;
  25424. sortLinked(p);
  25425. }
  25426. // Simon Tatham's linked list merge sort algorithm
  25427. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25428. function sortLinked(list) {
  25429. let numMerges;
  25430. let inSize = 1;
  25431. do {
  25432. let p = list;
  25433. let e;
  25434. list = null;
  25435. let tail = null;
  25436. numMerges = 0;
  25437. while (p) {
  25438. numMerges++;
  25439. let q = p;
  25440. let pSize = 0;
  25441. for (let i = 0; i < inSize; i++) {
  25442. pSize++;
  25443. q = q.nextZ;
  25444. if (!q) break;
  25445. }
  25446. let qSize = inSize;
  25447. while (pSize > 0 || (qSize > 0 && q)) {
  25448. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25449. e = p;
  25450. p = p.nextZ;
  25451. pSize--;
  25452. } else {
  25453. e = q;
  25454. q = q.nextZ;
  25455. qSize--;
  25456. }
  25457. if (tail) tail.nextZ = e;
  25458. else list = e;
  25459. e.prevZ = tail;
  25460. tail = e;
  25461. }
  25462. p = q;
  25463. }
  25464. tail.nextZ = null;
  25465. inSize *= 2;
  25466. } while (numMerges > 1);
  25467. return list;
  25468. }
  25469. // z-order of a point given coords and inverse of the longer side of data bbox
  25470. function zOrder(x, y, minX, minY, invSize) {
  25471. // coords are transformed into non-negative 15-bit integer range
  25472. x = (x - minX) * invSize | 0;
  25473. y = (y - minY) * invSize | 0;
  25474. x = (x | (x << 8)) & 0x00FF00FF;
  25475. x = (x | (x << 4)) & 0x0F0F0F0F;
  25476. x = (x | (x << 2)) & 0x33333333;
  25477. x = (x | (x << 1)) & 0x55555555;
  25478. y = (y | (y << 8)) & 0x00FF00FF;
  25479. y = (y | (y << 4)) & 0x0F0F0F0F;
  25480. y = (y | (y << 2)) & 0x33333333;
  25481. y = (y | (y << 1)) & 0x55555555;
  25482. return x | (y << 1);
  25483. }
  25484. // find the leftmost node of a polygon ring
  25485. function getLeftmost(start) {
  25486. let p = start,
  25487. leftmost = start;
  25488. do {
  25489. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25490. p = p.next;
  25491. } while (p !== start);
  25492. return leftmost;
  25493. }
  25494. // check if a point lies within a convex triangle
  25495. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25496. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25497. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25498. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25499. }
  25500. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25501. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25502. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25503. }
  25504. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25505. function isValidDiagonal(a, b) {
  25506. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25507. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25508. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25509. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25510. }
  25511. // signed area of a triangle
  25512. function area(p, q, r) {
  25513. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25514. }
  25515. // check if two points are equal
  25516. function equals(p1, p2) {
  25517. return p1.x === p2.x && p1.y === p2.y;
  25518. }
  25519. // check if two segments intersect
  25520. function intersects(p1, q1, p2, q2) {
  25521. const o1 = sign(area(p1, q1, p2));
  25522. const o2 = sign(area(p1, q1, q2));
  25523. const o3 = sign(area(p2, q2, p1));
  25524. const o4 = sign(area(p2, q2, q1));
  25525. if (o1 !== o2 && o3 !== o4) return true; // general case
  25526. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25527. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25528. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25529. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25530. return false;
  25531. }
  25532. // for collinear points p, q, r, check if point q lies on segment pr
  25533. function onSegment(p, q, r) {
  25534. 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);
  25535. }
  25536. function sign(num) {
  25537. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25538. }
  25539. // check if a polygon diagonal intersects any polygon segments
  25540. function intersectsPolygon(a, b) {
  25541. let p = a;
  25542. do {
  25543. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25544. intersects(p, p.next, a, b)) return true;
  25545. p = p.next;
  25546. } while (p !== a);
  25547. return false;
  25548. }
  25549. // check if a polygon diagonal is locally inside the polygon
  25550. function locallyInside(a, b) {
  25551. return area(a.prev, a, a.next) < 0 ?
  25552. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25553. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25554. }
  25555. // check if the middle point of a polygon diagonal is inside the polygon
  25556. function middleInside(a, b) {
  25557. let p = a;
  25558. let inside = false;
  25559. const px = (a.x + b.x) / 2;
  25560. const py = (a.y + b.y) / 2;
  25561. do {
  25562. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25563. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25564. inside = !inside;
  25565. p = p.next;
  25566. } while (p !== a);
  25567. return inside;
  25568. }
  25569. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25570. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25571. function splitPolygon(a, b) {
  25572. const a2 = createNode(a.i, a.x, a.y),
  25573. b2 = createNode(b.i, b.x, b.y),
  25574. an = a.next,
  25575. bp = b.prev;
  25576. a.next = b;
  25577. b.prev = a;
  25578. a2.next = an;
  25579. an.prev = a2;
  25580. b2.next = a2;
  25581. a2.prev = b2;
  25582. bp.next = b2;
  25583. b2.prev = bp;
  25584. return b2;
  25585. }
  25586. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25587. function insertNode(i, x, y, last) {
  25588. const p = createNode(i, x, y);
  25589. if (!last) {
  25590. p.prev = p;
  25591. p.next = p;
  25592. } else {
  25593. p.next = last.next;
  25594. p.prev = last;
  25595. last.next.prev = p;
  25596. last.next = p;
  25597. }
  25598. return p;
  25599. }
  25600. function removeNode(p) {
  25601. p.next.prev = p.prev;
  25602. p.prev.next = p.next;
  25603. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25604. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25605. }
  25606. function createNode(i, x, y) {
  25607. return {
  25608. i, // vertex index in coordinates array
  25609. x, y, // vertex coordinates
  25610. prev: null, // previous and next vertex nodes in a polygon ring
  25611. next: null,
  25612. z: 0, // z-order curve value
  25613. prevZ: null, // previous and next nodes in z-order
  25614. nextZ: null,
  25615. steiner: false // indicates whether this is a steiner point
  25616. };
  25617. }
  25618. function signedArea(data, start, end, dim) {
  25619. let sum = 0;
  25620. for (let i = start, j = end - dim; i < end; i += dim) {
  25621. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25622. j = i;
  25623. }
  25624. return sum;
  25625. }
  25626. class Earcut {
  25627. /**
  25628. * Triangulates the given shape definition by returning an array of triangles.
  25629. *
  25630. * @param {Array<number>} data - An array with 2D points.
  25631. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25632. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25633. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25634. * representing vertex indices.
  25635. */
  25636. static triangulate( data, holeIndices, dim = 2 ) {
  25637. return earcut( data, holeIndices, dim );
  25638. }
  25639. }
  25640. /**
  25641. * A class containing utility functions for shapes.
  25642. *
  25643. * @hideconstructor
  25644. */
  25645. class ShapeUtils {
  25646. /**
  25647. * Calculate area of a ( 2D ) contour polygon.
  25648. *
  25649. * @param {Array<Vector2>} contour - An array of 2D points.
  25650. * @return {number} The area.
  25651. */
  25652. static area( contour ) {
  25653. const n = contour.length;
  25654. let a = 0.0;
  25655. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25656. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25657. }
  25658. return a * 0.5;
  25659. }
  25660. /**
  25661. * Returns `true` if the given contour uses a clockwise winding order.
  25662. *
  25663. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25664. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25665. */
  25666. static isClockWise( pts ) {
  25667. return ShapeUtils.area( pts ) < 0;
  25668. }
  25669. /**
  25670. * Triangulates the given shape definition.
  25671. *
  25672. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25673. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25674. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25675. */
  25676. static triangulateShape( contour, holes ) {
  25677. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25678. const holeIndices = []; // array of hole indices
  25679. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25680. removeDupEndPts( contour );
  25681. addContour( vertices, contour );
  25682. //
  25683. let holeIndex = contour.length;
  25684. holes.forEach( removeDupEndPts );
  25685. for ( let i = 0; i < holes.length; i ++ ) {
  25686. holeIndices.push( holeIndex );
  25687. holeIndex += holes[ i ].length;
  25688. addContour( vertices, holes[ i ] );
  25689. }
  25690. //
  25691. const triangles = Earcut.triangulate( vertices, holeIndices );
  25692. //
  25693. for ( let i = 0; i < triangles.length; i += 3 ) {
  25694. faces.push( triangles.slice( i, i + 3 ) );
  25695. }
  25696. return faces;
  25697. }
  25698. }
  25699. function removeDupEndPts( points ) {
  25700. const l = points.length;
  25701. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25702. points.pop();
  25703. }
  25704. }
  25705. function addContour( vertices, contour ) {
  25706. for ( let i = 0; i < contour.length; i ++ ) {
  25707. vertices.push( contour[ i ].x );
  25708. vertices.push( contour[ i ].y );
  25709. }
  25710. }
  25711. /**
  25712. * Creates extruded geometry from a path shape.
  25713. *
  25714. * ```js
  25715. * const length = 12, width = 8;
  25716. *
  25717. * const shape = new THREE.Shape();
  25718. * shape.moveTo( 0,0 );
  25719. * shape.lineTo( 0, width );
  25720. * shape.lineTo( length, width );
  25721. * shape.lineTo( length, 0 );
  25722. * shape.lineTo( 0, 0 );
  25723. *
  25724. * const geometry = new THREE.ExtrudeGeometry( shape );
  25725. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25726. * const mesh = new THREE.Mesh( geometry, material ) ;
  25727. * scene.add( mesh );
  25728. * ```
  25729. *
  25730. * @augments BufferGeometry
  25731. */
  25732. class ExtrudeGeometry extends BufferGeometry {
  25733. /**
  25734. * Constructs a new extrude geometry.
  25735. *
  25736. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25737. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25738. */
  25739. 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 = {} ) {
  25740. super();
  25741. this.type = 'ExtrudeGeometry';
  25742. /**
  25743. * Holds the constructor parameters that have been
  25744. * used to generate the geometry. Any modification
  25745. * after instantiation does not change the geometry.
  25746. *
  25747. * @type {Object}
  25748. */
  25749. this.parameters = {
  25750. shapes: shapes,
  25751. options: options
  25752. };
  25753. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25754. const scope = this;
  25755. const verticesArray = [];
  25756. const uvArray = [];
  25757. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25758. const shape = shapes[ i ];
  25759. addShape( shape );
  25760. }
  25761. // build geometry
  25762. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25763. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25764. this.computeVertexNormals();
  25765. // functions
  25766. function addShape( shape ) {
  25767. const placeholder = [];
  25768. // options
  25769. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25770. const steps = options.steps !== undefined ? options.steps : 1;
  25771. const depth = options.depth !== undefined ? options.depth : 1;
  25772. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25773. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25774. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25775. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25776. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25777. const extrudePath = options.extrudePath;
  25778. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25779. //
  25780. let extrudePts, extrudeByPath = false;
  25781. let splineTube, binormal, normal, position2;
  25782. if ( extrudePath ) {
  25783. extrudePts = extrudePath.getSpacedPoints( steps );
  25784. extrudeByPath = true;
  25785. bevelEnabled = false; // bevels not supported for path extrusion
  25786. // SETUP TNB variables
  25787. // TODO1 - have a .isClosed in spline?
  25788. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25789. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25790. binormal = new Vector3();
  25791. normal = new Vector3();
  25792. position2 = new Vector3();
  25793. }
  25794. // Safeguards if bevels are not enabled
  25795. if ( ! bevelEnabled ) {
  25796. bevelSegments = 0;
  25797. bevelThickness = 0;
  25798. bevelSize = 0;
  25799. bevelOffset = 0;
  25800. }
  25801. // Variables initialization
  25802. const shapePoints = shape.extractPoints( curveSegments );
  25803. let vertices = shapePoints.shape;
  25804. const holes = shapePoints.holes;
  25805. const reverse = ! ShapeUtils.isClockWise( vertices );
  25806. if ( reverse ) {
  25807. vertices = vertices.reverse();
  25808. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25809. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25810. const ahole = holes[ h ];
  25811. if ( ShapeUtils.isClockWise( ahole ) ) {
  25812. holes[ h ] = ahole.reverse();
  25813. }
  25814. }
  25815. }
  25816. /**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.
  25817. * @param {Array<Vector2>} points
  25818. */
  25819. function mergeOverlappingPoints( points ) {
  25820. const THRESHOLD = 1e-10;
  25821. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25822. let prevPos = points[ 0 ];
  25823. for ( let i = 1; i <= points.length; i ++ ) {
  25824. const currentIndex = i % points.length;
  25825. const currentPos = points[ currentIndex ];
  25826. const dx = currentPos.x - prevPos.x;
  25827. const dy = currentPos.y - prevPos.y;
  25828. const distSq = dx * dx + dy * dy;
  25829. const scalingFactorSqrt = Math.max(
  25830. Math.abs( currentPos.x ),
  25831. Math.abs( currentPos.y ),
  25832. Math.abs( prevPos.x ),
  25833. Math.abs( prevPos.y )
  25834. );
  25835. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25836. if ( distSq <= thresholdSqScaled ) {
  25837. points.splice( currentIndex, 1 );
  25838. i --;
  25839. continue;
  25840. }
  25841. prevPos = currentPos;
  25842. }
  25843. }
  25844. mergeOverlappingPoints( vertices );
  25845. holes.forEach( mergeOverlappingPoints );
  25846. const numHoles = holes.length;
  25847. /* Vertices */
  25848. const contour = vertices; // vertices has all points but contour has only points of circumference
  25849. for ( let h = 0; h < numHoles; h ++ ) {
  25850. const ahole = holes[ h ];
  25851. vertices = vertices.concat( ahole );
  25852. }
  25853. function scalePt2( pt, vec, size ) {
  25854. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  25855. return pt.clone().addScaledVector( vec, size );
  25856. }
  25857. const vlen = vertices.length;
  25858. // Find directions for point movement
  25859. function getBevelVec( inPt, inPrev, inNext ) {
  25860. // computes for inPt the corresponding point inPt' on a new contour
  25861. // shifted by 1 unit (length of normalized vector) to the left
  25862. // if we walk along contour clockwise, this new contour is outside the old one
  25863. //
  25864. // inPt' is the intersection of the two lines parallel to the two
  25865. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25866. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25867. // good reading for geometry algorithms (here: line-line intersection)
  25868. // http://geomalgorithms.com/a05-_intersect-1.html
  25869. const v_prev_x = inPt.x - inPrev.x,
  25870. v_prev_y = inPt.y - inPrev.y;
  25871. const v_next_x = inNext.x - inPt.x,
  25872. v_next_y = inNext.y - inPt.y;
  25873. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25874. // check for collinear edges
  25875. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25876. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25877. // not collinear
  25878. // length of vectors for normalizing
  25879. const v_prev_len = Math.sqrt( v_prev_lensq );
  25880. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25881. // shift adjacent points by unit vectors to the left
  25882. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25883. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25884. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25885. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25886. // scaling factor for v_prev to intersection point
  25887. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25888. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25889. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25890. // vector from inPt to intersection point
  25891. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25892. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25893. // Don't normalize!, otherwise sharp corners become ugly
  25894. // but prevent crazy spikes
  25895. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25896. if ( v_trans_lensq <= 2 ) {
  25897. return new Vector2( v_trans_x, v_trans_y );
  25898. } else {
  25899. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25900. }
  25901. } else {
  25902. // handle special case of collinear edges
  25903. let direction_eq = false; // assumes: opposite
  25904. if ( v_prev_x > Number.EPSILON ) {
  25905. if ( v_next_x > Number.EPSILON ) {
  25906. direction_eq = true;
  25907. }
  25908. } else {
  25909. if ( v_prev_x < - Number.EPSILON ) {
  25910. if ( v_next_x < - Number.EPSILON ) {
  25911. direction_eq = true;
  25912. }
  25913. } else {
  25914. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25915. direction_eq = true;
  25916. }
  25917. }
  25918. }
  25919. if ( direction_eq ) {
  25920. // console.log("Warning: lines are a straight sequence");
  25921. v_trans_x = - v_prev_y;
  25922. v_trans_y = v_prev_x;
  25923. shrink_by = Math.sqrt( v_prev_lensq );
  25924. } else {
  25925. // console.log("Warning: lines are a straight spike");
  25926. v_trans_x = v_prev_x;
  25927. v_trans_y = v_prev_y;
  25928. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25929. }
  25930. }
  25931. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25932. }
  25933. const contourMovements = [];
  25934. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25935. if ( j === il ) j = 0;
  25936. if ( k === il ) k = 0;
  25937. // (j)---(i)---(k)
  25938. // console.log('i,j,k', i, j , k)
  25939. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25940. }
  25941. const holesMovements = [];
  25942. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25943. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25944. const ahole = holes[ h ];
  25945. oneHoleMovements = [];
  25946. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25947. if ( j === il ) j = 0;
  25948. if ( k === il ) k = 0;
  25949. // (j)---(i)---(k)
  25950. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25951. }
  25952. holesMovements.push( oneHoleMovements );
  25953. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25954. }
  25955. let faces;
  25956. if ( bevelSegments === 0 ) {
  25957. faces = ShapeUtils.triangulateShape( contour, holes );
  25958. } else {
  25959. const contractedContourVertices = [];
  25960. const expandedHoleVertices = [];
  25961. // Loop bevelSegments, 1 for the front, 1 for the back
  25962. for ( let b = 0; b < bevelSegments; b ++ ) {
  25963. //for ( b = bevelSegments; b > 0; b -- ) {
  25964. const t = b / bevelSegments;
  25965. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25966. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25967. // contract shape
  25968. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25969. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25970. v( vert.x, vert.y, - z );
  25971. if ( t === 0 ) contractedContourVertices.push( vert );
  25972. }
  25973. // expand holes
  25974. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25975. const ahole = holes[ h ];
  25976. oneHoleMovements = holesMovements[ h ];
  25977. const oneHoleVertices = [];
  25978. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25979. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25980. v( vert.x, vert.y, - z );
  25981. if ( t === 0 ) oneHoleVertices.push( vert );
  25982. }
  25983. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25984. }
  25985. }
  25986. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25987. }
  25988. const flen = faces.length;
  25989. const bs = bevelSize + bevelOffset;
  25990. // Back facing vertices
  25991. for ( let i = 0; i < vlen; i ++ ) {
  25992. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25993. if ( ! extrudeByPath ) {
  25994. v( vert.x, vert.y, 0 );
  25995. } else {
  25996. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25997. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25998. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25999. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  26000. v( position2.x, position2.y, position2.z );
  26001. }
  26002. }
  26003. // Add stepped vertices...
  26004. // Including front facing vertices
  26005. for ( let s = 1; s <= steps; s ++ ) {
  26006. for ( let i = 0; i < vlen; i ++ ) {
  26007. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26008. if ( ! extrudeByPath ) {
  26009. v( vert.x, vert.y, depth / steps * s );
  26010. } else {
  26011. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  26012. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  26013. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  26014. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  26015. v( position2.x, position2.y, position2.z );
  26016. }
  26017. }
  26018. }
  26019. // Add bevel segments planes
  26020. //for ( b = 1; b <= bevelSegments; b ++ ) {
  26021. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  26022. const t = b / bevelSegments;
  26023. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26024. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26025. // contract shape
  26026. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26027. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26028. v( vert.x, vert.y, depth + z );
  26029. }
  26030. // expand holes
  26031. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26032. const ahole = holes[ h ];
  26033. oneHoleMovements = holesMovements[ h ];
  26034. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26035. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26036. if ( ! extrudeByPath ) {
  26037. v( vert.x, vert.y, depth + z );
  26038. } else {
  26039. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  26040. }
  26041. }
  26042. }
  26043. }
  26044. /* Faces */
  26045. // Top and bottom faces
  26046. buildLidFaces();
  26047. // Sides faces
  26048. buildSideFaces();
  26049. ///// Internal functions
  26050. function buildLidFaces() {
  26051. const start = verticesArray.length / 3;
  26052. if ( bevelEnabled ) {
  26053. let layer = 0; // steps + 1
  26054. let offset = vlen * layer;
  26055. // Bottom faces
  26056. for ( let i = 0; i < flen; i ++ ) {
  26057. const face = faces[ i ];
  26058. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26059. }
  26060. layer = steps + bevelSegments * 2;
  26061. offset = vlen * layer;
  26062. // Top faces
  26063. for ( let i = 0; i < flen; i ++ ) {
  26064. const face = faces[ i ];
  26065. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26066. }
  26067. } else {
  26068. // Bottom faces
  26069. for ( let i = 0; i < flen; i ++ ) {
  26070. const face = faces[ i ];
  26071. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26072. }
  26073. // Top faces
  26074. for ( let i = 0; i < flen; i ++ ) {
  26075. const face = faces[ i ];
  26076. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26077. }
  26078. }
  26079. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26080. }
  26081. // Create faces for the z-sides of the shape
  26082. function buildSideFaces() {
  26083. const start = verticesArray.length / 3;
  26084. let layeroffset = 0;
  26085. sidewalls( contour, layeroffset );
  26086. layeroffset += contour.length;
  26087. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26088. const ahole = holes[ h ];
  26089. sidewalls( ahole, layeroffset );
  26090. //, true
  26091. layeroffset += ahole.length;
  26092. }
  26093. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26094. }
  26095. function sidewalls( contour, layeroffset ) {
  26096. let i = contour.length;
  26097. while ( -- i >= 0 ) {
  26098. const j = i;
  26099. let k = i - 1;
  26100. if ( k < 0 ) k = contour.length - 1;
  26101. //console.log('b', i,j, i-1, k,vertices.length);
  26102. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26103. const slen1 = vlen * s;
  26104. const slen2 = vlen * ( s + 1 );
  26105. const a = layeroffset + j + slen1,
  26106. b = layeroffset + k + slen1,
  26107. c = layeroffset + k + slen2,
  26108. d = layeroffset + j + slen2;
  26109. f4( a, b, c, d );
  26110. }
  26111. }
  26112. }
  26113. function v( x, y, z ) {
  26114. placeholder.push( x );
  26115. placeholder.push( y );
  26116. placeholder.push( z );
  26117. }
  26118. function f3( a, b, c ) {
  26119. addVertex( a );
  26120. addVertex( b );
  26121. addVertex( c );
  26122. const nextIndex = verticesArray.length / 3;
  26123. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26124. addUV( uvs[ 0 ] );
  26125. addUV( uvs[ 1 ] );
  26126. addUV( uvs[ 2 ] );
  26127. }
  26128. function f4( a, b, c, d ) {
  26129. addVertex( a );
  26130. addVertex( b );
  26131. addVertex( d );
  26132. addVertex( b );
  26133. addVertex( c );
  26134. addVertex( d );
  26135. const nextIndex = verticesArray.length / 3;
  26136. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26137. addUV( uvs[ 0 ] );
  26138. addUV( uvs[ 1 ] );
  26139. addUV( uvs[ 3 ] );
  26140. addUV( uvs[ 1 ] );
  26141. addUV( uvs[ 2 ] );
  26142. addUV( uvs[ 3 ] );
  26143. }
  26144. function addVertex( index ) {
  26145. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26146. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26147. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26148. }
  26149. function addUV( vector2 ) {
  26150. uvArray.push( vector2.x );
  26151. uvArray.push( vector2.y );
  26152. }
  26153. }
  26154. }
  26155. copy( source ) {
  26156. super.copy( source );
  26157. this.parameters = Object.assign( {}, source.parameters );
  26158. return this;
  26159. }
  26160. toJSON() {
  26161. const data = super.toJSON();
  26162. const shapes = this.parameters.shapes;
  26163. const options = this.parameters.options;
  26164. return toJSON$1( shapes, options, data );
  26165. }
  26166. /**
  26167. * Factory method for creating an instance of this class from the given
  26168. * JSON object.
  26169. *
  26170. * @param {Object} data - A JSON object representing the serialized geometry.
  26171. * @param {Array<Shape>} shapes - An array of shapes.
  26172. * @return {ExtrudeGeometry} A new instance.
  26173. */
  26174. static fromJSON( data, shapes ) {
  26175. const geometryShapes = [];
  26176. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26177. const shape = shapes[ data.shapes[ j ] ];
  26178. geometryShapes.push( shape );
  26179. }
  26180. const extrudePath = data.options.extrudePath;
  26181. if ( extrudePath !== undefined ) {
  26182. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26183. }
  26184. return new ExtrudeGeometry( geometryShapes, data.options );
  26185. }
  26186. }
  26187. const WorldUVGenerator = {
  26188. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26189. const a_x = vertices[ indexA * 3 ];
  26190. const a_y = vertices[ indexA * 3 + 1 ];
  26191. const b_x = vertices[ indexB * 3 ];
  26192. const b_y = vertices[ indexB * 3 + 1 ];
  26193. const c_x = vertices[ indexC * 3 ];
  26194. const c_y = vertices[ indexC * 3 + 1 ];
  26195. return [
  26196. new Vector2( a_x, a_y ),
  26197. new Vector2( b_x, b_y ),
  26198. new Vector2( c_x, c_y )
  26199. ];
  26200. },
  26201. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26202. const a_x = vertices[ indexA * 3 ];
  26203. const a_y = vertices[ indexA * 3 + 1 ];
  26204. const a_z = vertices[ indexA * 3 + 2 ];
  26205. const b_x = vertices[ indexB * 3 ];
  26206. const b_y = vertices[ indexB * 3 + 1 ];
  26207. const b_z = vertices[ indexB * 3 + 2 ];
  26208. const c_x = vertices[ indexC * 3 ];
  26209. const c_y = vertices[ indexC * 3 + 1 ];
  26210. const c_z = vertices[ indexC * 3 + 2 ];
  26211. const d_x = vertices[ indexD * 3 ];
  26212. const d_y = vertices[ indexD * 3 + 1 ];
  26213. const d_z = vertices[ indexD * 3 + 2 ];
  26214. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26215. return [
  26216. new Vector2( a_x, 1 - a_z ),
  26217. new Vector2( b_x, 1 - b_z ),
  26218. new Vector2( c_x, 1 - c_z ),
  26219. new Vector2( d_x, 1 - d_z )
  26220. ];
  26221. } else {
  26222. return [
  26223. new Vector2( a_y, 1 - a_z ),
  26224. new Vector2( b_y, 1 - b_z ),
  26225. new Vector2( c_y, 1 - c_z ),
  26226. new Vector2( d_y, 1 - d_z )
  26227. ];
  26228. }
  26229. }
  26230. };
  26231. function toJSON$1( shapes, options, data ) {
  26232. data.shapes = [];
  26233. if ( Array.isArray( shapes ) ) {
  26234. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26235. const shape = shapes[ i ];
  26236. data.shapes.push( shape.uuid );
  26237. }
  26238. } else {
  26239. data.shapes.push( shapes.uuid );
  26240. }
  26241. data.options = Object.assign( {}, options );
  26242. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26243. return data;
  26244. }
  26245. /**
  26246. * A geometry class for representing an icosahedron.
  26247. *
  26248. * ```js
  26249. * const geometry = new THREE.IcosahedronGeometry();
  26250. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26251. * const icosahedron = new THREE.Mesh( geometry, material );
  26252. * scene.add( icosahedron );
  26253. * ```
  26254. *
  26255. * @augments PolyhedronGeometry
  26256. */
  26257. class IcosahedronGeometry extends PolyhedronGeometry {
  26258. /**
  26259. * Constructs a new icosahedron geometry.
  26260. *
  26261. * @param {number} [radius=1] - Radius of the icosahedron.
  26262. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26263. */
  26264. constructor( radius = 1, detail = 0 ) {
  26265. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26266. const vertices = [
  26267. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26268. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26269. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26270. ];
  26271. const indices = [
  26272. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26273. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26274. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26275. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26276. ];
  26277. super( vertices, indices, radius, detail );
  26278. this.type = 'IcosahedronGeometry';
  26279. /**
  26280. * Holds the constructor parameters that have been
  26281. * used to generate the geometry. Any modification
  26282. * after instantiation does not change the geometry.
  26283. *
  26284. * @type {Object}
  26285. */
  26286. this.parameters = {
  26287. radius: radius,
  26288. detail: detail
  26289. };
  26290. }
  26291. /**
  26292. * Factory method for creating an instance of this class from the given
  26293. * JSON object.
  26294. *
  26295. * @param {Object} data - A JSON object representing the serialized geometry.
  26296. * @return {IcosahedronGeometry} A new instance.
  26297. */
  26298. static fromJSON( data ) {
  26299. return new IcosahedronGeometry( data.radius, data.detail );
  26300. }
  26301. }
  26302. /**
  26303. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26304. *
  26305. * ```js
  26306. * const points = [];
  26307. * for ( let i = 0; i < 10; i ++ ) {
  26308. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26309. * }
  26310. * const geometry = new THREE.LatheGeometry( points );
  26311. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26312. * const lathe = new THREE.Mesh( geometry, material );
  26313. * scene.add( lathe );
  26314. * ```
  26315. *
  26316. * @augments BufferGeometry
  26317. */
  26318. class LatheGeometry extends BufferGeometry {
  26319. /**
  26320. * Constructs a new lathe geometry.
  26321. *
  26322. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26323. * must be greater than zero.
  26324. * @param {number} [segments=12] - The number of circumference segments to generate.
  26325. * @param {number} [phiStart=0] - The starting angle in radians.
  26326. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26327. * closed lathe, less than 2PI is a portion.
  26328. */
  26329. 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 ) {
  26330. super();
  26331. this.type = 'LatheGeometry';
  26332. /**
  26333. * Holds the constructor parameters that have been
  26334. * used to generate the geometry. Any modification
  26335. * after instantiation does not change the geometry.
  26336. *
  26337. * @type {Object}
  26338. */
  26339. this.parameters = {
  26340. points: points,
  26341. segments: segments,
  26342. phiStart: phiStart,
  26343. phiLength: phiLength
  26344. };
  26345. segments = Math.floor( segments );
  26346. // clamp phiLength so it's in range of [ 0, 2PI ]
  26347. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26348. // buffers
  26349. const indices = [];
  26350. const vertices = [];
  26351. const uvs = [];
  26352. const initNormals = [];
  26353. const normals = [];
  26354. // helper variables
  26355. const inverseSegments = 1.0 / segments;
  26356. const vertex = new Vector3();
  26357. const uv = new Vector2();
  26358. const normal = new Vector3();
  26359. const curNormal = new Vector3();
  26360. const prevNormal = new Vector3();
  26361. let dx = 0;
  26362. let dy = 0;
  26363. // pre-compute normals for initial "meridian"
  26364. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26365. switch ( j ) {
  26366. case 0: // special handling for 1st vertex on path
  26367. dx = points[ j + 1 ].x - points[ j ].x;
  26368. dy = points[ j + 1 ].y - points[ j ].y;
  26369. normal.x = dy * 1.0;
  26370. normal.y = - dx;
  26371. normal.z = dy * 0.0;
  26372. prevNormal.copy( normal );
  26373. normal.normalize();
  26374. initNormals.push( normal.x, normal.y, normal.z );
  26375. break;
  26376. case ( points.length - 1 ): // special handling for last Vertex on path
  26377. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26378. break;
  26379. default: // default handling for all vertices in between
  26380. dx = points[ j + 1 ].x - points[ j ].x;
  26381. dy = points[ j + 1 ].y - points[ j ].y;
  26382. normal.x = dy * 1.0;
  26383. normal.y = - dx;
  26384. normal.z = dy * 0.0;
  26385. curNormal.copy( normal );
  26386. normal.x += prevNormal.x;
  26387. normal.y += prevNormal.y;
  26388. normal.z += prevNormal.z;
  26389. normal.normalize();
  26390. initNormals.push( normal.x, normal.y, normal.z );
  26391. prevNormal.copy( curNormal );
  26392. }
  26393. }
  26394. // generate vertices, uvs and normals
  26395. for ( let i = 0; i <= segments; i ++ ) {
  26396. const phi = phiStart + i * inverseSegments * phiLength;
  26397. const sin = Math.sin( phi );
  26398. const cos = Math.cos( phi );
  26399. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26400. // vertex
  26401. vertex.x = points[ j ].x * sin;
  26402. vertex.y = points[ j ].y;
  26403. vertex.z = points[ j ].x * cos;
  26404. vertices.push( vertex.x, vertex.y, vertex.z );
  26405. // uv
  26406. uv.x = i / segments;
  26407. uv.y = j / ( points.length - 1 );
  26408. uvs.push( uv.x, uv.y );
  26409. // normal
  26410. const x = initNormals[ 3 * j + 0 ] * sin;
  26411. const y = initNormals[ 3 * j + 1 ];
  26412. const z = initNormals[ 3 * j + 0 ] * cos;
  26413. normals.push( x, y, z );
  26414. }
  26415. }
  26416. // indices
  26417. for ( let i = 0; i < segments; i ++ ) {
  26418. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26419. const base = j + i * points.length;
  26420. const a = base;
  26421. const b = base + points.length;
  26422. const c = base + points.length + 1;
  26423. const d = base + 1;
  26424. // faces
  26425. indices.push( a, b, d );
  26426. indices.push( c, d, b );
  26427. }
  26428. }
  26429. // build geometry
  26430. this.setIndex( indices );
  26431. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26432. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26433. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26434. }
  26435. copy( source ) {
  26436. super.copy( source );
  26437. this.parameters = Object.assign( {}, source.parameters );
  26438. return this;
  26439. }
  26440. /**
  26441. * Factory method for creating an instance of this class from the given
  26442. * JSON object.
  26443. *
  26444. * @param {Object} data - A JSON object representing the serialized geometry.
  26445. * @return {LatheGeometry} A new instance.
  26446. */
  26447. static fromJSON( data ) {
  26448. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26449. }
  26450. }
  26451. /**
  26452. * A geometry class for representing an octahedron.
  26453. *
  26454. * ```js
  26455. * const geometry = new THREE.OctahedronGeometry();
  26456. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26457. * const octahedron = new THREE.Mesh( geometry, material );
  26458. * scene.add( octahedron );
  26459. * ```
  26460. *
  26461. * @augments PolyhedronGeometry
  26462. */
  26463. class OctahedronGeometry extends PolyhedronGeometry {
  26464. /**
  26465. * Constructs a new octahedron geometry.
  26466. *
  26467. * @param {number} [radius=1] - Radius of the octahedron.
  26468. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26469. */
  26470. constructor( radius = 1, detail = 0 ) {
  26471. const vertices = [
  26472. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26473. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26474. ];
  26475. const indices = [
  26476. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26477. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26478. 1, 3, 4, 1, 4, 2
  26479. ];
  26480. super( vertices, indices, radius, detail );
  26481. this.type = 'OctahedronGeometry';
  26482. /**
  26483. * Holds the constructor parameters that have been
  26484. * used to generate the geometry. Any modification
  26485. * after instantiation does not change the geometry.
  26486. *
  26487. * @type {Object}
  26488. */
  26489. this.parameters = {
  26490. radius: radius,
  26491. detail: detail
  26492. };
  26493. }
  26494. /**
  26495. * Factory method for creating an instance of this class from the given
  26496. * JSON object.
  26497. *
  26498. * @param {Object} data - A JSON object representing the serialized geometry.
  26499. * @return {OctahedronGeometry} A new instance.
  26500. */
  26501. static fromJSON( data ) {
  26502. return new OctahedronGeometry( data.radius, data.detail );
  26503. }
  26504. }
  26505. /**
  26506. * A geometry class for representing a plane.
  26507. *
  26508. * ```js
  26509. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26510. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26511. * const plane = new THREE.Mesh( geometry, material );
  26512. * scene.add( plane );
  26513. * ```
  26514. *
  26515. * @augments BufferGeometry
  26516. */
  26517. class PlaneGeometry extends BufferGeometry {
  26518. /**
  26519. * Constructs a new plane geometry.
  26520. *
  26521. * @param {number} [width=1] - The width along the X axis.
  26522. * @param {number} [height=1] - The height along the Y axis
  26523. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26524. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26525. */
  26526. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26527. super();
  26528. this.type = 'PlaneGeometry';
  26529. /**
  26530. * Holds the constructor parameters that have been
  26531. * used to generate the geometry. Any modification
  26532. * after instantiation does not change the geometry.
  26533. *
  26534. * @type {Object}
  26535. */
  26536. this.parameters = {
  26537. width: width,
  26538. height: height,
  26539. widthSegments: widthSegments,
  26540. heightSegments: heightSegments
  26541. };
  26542. const width_half = width / 2;
  26543. const height_half = height / 2;
  26544. const gridX = Math.floor( widthSegments );
  26545. const gridY = Math.floor( heightSegments );
  26546. const gridX1 = gridX + 1;
  26547. const gridY1 = gridY + 1;
  26548. const segment_width = width / gridX;
  26549. const segment_height = height / gridY;
  26550. //
  26551. const indices = [];
  26552. const vertices = [];
  26553. const normals = [];
  26554. const uvs = [];
  26555. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26556. const y = iy * segment_height - height_half;
  26557. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26558. const x = ix * segment_width - width_half;
  26559. vertices.push( x, - y, 0 );
  26560. normals.push( 0, 0, 1 );
  26561. uvs.push( ix / gridX );
  26562. uvs.push( 1 - ( iy / gridY ) );
  26563. }
  26564. }
  26565. for ( let iy = 0; iy < gridY; iy ++ ) {
  26566. for ( let ix = 0; ix < gridX; ix ++ ) {
  26567. const a = ix + gridX1 * iy;
  26568. const b = ix + gridX1 * ( iy + 1 );
  26569. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26570. const d = ( ix + 1 ) + gridX1 * iy;
  26571. indices.push( a, b, d );
  26572. indices.push( b, c, d );
  26573. }
  26574. }
  26575. this.setIndex( indices );
  26576. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26577. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26578. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26579. }
  26580. copy( source ) {
  26581. super.copy( source );
  26582. this.parameters = Object.assign( {}, source.parameters );
  26583. return this;
  26584. }
  26585. /**
  26586. * Factory method for creating an instance of this class from the given
  26587. * JSON object.
  26588. *
  26589. * @param {Object} data - A JSON object representing the serialized geometry.
  26590. * @return {PlaneGeometry} A new instance.
  26591. */
  26592. static fromJSON( data ) {
  26593. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26594. }
  26595. }
  26596. /**
  26597. * A class for generating a two-dimensional ring geometry.
  26598. *
  26599. * ```js
  26600. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26601. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26602. * const mesh = new THREE.Mesh( geometry, material );
  26603. * scene.add( mesh );
  26604. * ```
  26605. *
  26606. * @augments BufferGeometry
  26607. */
  26608. class RingGeometry extends BufferGeometry {
  26609. /**
  26610. * Constructs a new ring geometry.
  26611. *
  26612. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26613. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26614. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26615. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26616. * @param {number} [thetaStart=0] - Starting angle in radians.
  26617. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26618. */
  26619. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26620. super();
  26621. this.type = 'RingGeometry';
  26622. /**
  26623. * Holds the constructor parameters that have been
  26624. * used to generate the geometry. Any modification
  26625. * after instantiation does not change the geometry.
  26626. *
  26627. * @type {Object}
  26628. */
  26629. this.parameters = {
  26630. innerRadius: innerRadius,
  26631. outerRadius: outerRadius,
  26632. thetaSegments: thetaSegments,
  26633. phiSegments: phiSegments,
  26634. thetaStart: thetaStart,
  26635. thetaLength: thetaLength
  26636. };
  26637. thetaSegments = Math.max( 3, thetaSegments );
  26638. phiSegments = Math.max( 1, phiSegments );
  26639. // buffers
  26640. const indices = [];
  26641. const vertices = [];
  26642. const normals = [];
  26643. const uvs = [];
  26644. // some helper variables
  26645. let radius = innerRadius;
  26646. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26647. const vertex = new Vector3();
  26648. const uv = new Vector2();
  26649. // generate vertices, normals and uvs
  26650. for ( let j = 0; j <= phiSegments; j ++ ) {
  26651. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26652. // values are generate from the inside of the ring to the outside
  26653. const segment = thetaStart + i / thetaSegments * thetaLength;
  26654. // vertex
  26655. vertex.x = radius * Math.cos( segment );
  26656. vertex.y = radius * Math.sin( segment );
  26657. vertices.push( vertex.x, vertex.y, vertex.z );
  26658. // normal
  26659. normals.push( 0, 0, 1 );
  26660. // uv
  26661. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26662. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26663. uvs.push( uv.x, uv.y );
  26664. }
  26665. // increase the radius for next row of vertices
  26666. radius += radiusStep;
  26667. }
  26668. // indices
  26669. for ( let j = 0; j < phiSegments; j ++ ) {
  26670. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26671. for ( let i = 0; i < thetaSegments; i ++ ) {
  26672. const segment = i + thetaSegmentLevel;
  26673. const a = segment;
  26674. const b = segment + thetaSegments + 1;
  26675. const c = segment + thetaSegments + 2;
  26676. const d = segment + 1;
  26677. // faces
  26678. indices.push( a, b, d );
  26679. indices.push( b, c, d );
  26680. }
  26681. }
  26682. // build geometry
  26683. this.setIndex( indices );
  26684. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26685. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26686. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26687. }
  26688. copy( source ) {
  26689. super.copy( source );
  26690. this.parameters = Object.assign( {}, source.parameters );
  26691. return this;
  26692. }
  26693. /**
  26694. * Factory method for creating an instance of this class from the given
  26695. * JSON object.
  26696. *
  26697. * @param {Object} data - A JSON object representing the serialized geometry.
  26698. * @return {RingGeometry} A new instance.
  26699. */
  26700. static fromJSON( data ) {
  26701. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26702. }
  26703. }
  26704. /**
  26705. * Creates an one-sided polygonal geometry from one or more path shapes.
  26706. *
  26707. * ```js
  26708. * const arcShape = new THREE.Shape()
  26709. * .moveTo( 5, 1 )
  26710. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26711. *
  26712. * const geometry = new THREE.ShapeGeometry( arcShape );
  26713. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26714. * const mesh = new THREE.Mesh( geometry, material ) ;
  26715. * scene.add( mesh );
  26716. * ```
  26717. *
  26718. * @augments BufferGeometry
  26719. */
  26720. class ShapeGeometry extends BufferGeometry {
  26721. /**
  26722. * Constructs a new shape geometry.
  26723. *
  26724. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26725. * @param {number} [curveSegments=12] - Number of segments per shape.
  26726. */
  26727. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26728. super();
  26729. this.type = 'ShapeGeometry';
  26730. /**
  26731. * Holds the constructor parameters that have been
  26732. * used to generate the geometry. Any modification
  26733. * after instantiation does not change the geometry.
  26734. *
  26735. * @type {Object}
  26736. */
  26737. this.parameters = {
  26738. shapes: shapes,
  26739. curveSegments: curveSegments
  26740. };
  26741. // buffers
  26742. const indices = [];
  26743. const vertices = [];
  26744. const normals = [];
  26745. const uvs = [];
  26746. // helper variables
  26747. let groupStart = 0;
  26748. let groupCount = 0;
  26749. // allow single and array values for "shapes" parameter
  26750. if ( Array.isArray( shapes ) === false ) {
  26751. addShape( shapes );
  26752. } else {
  26753. for ( let i = 0; i < shapes.length; i ++ ) {
  26754. addShape( shapes[ i ] );
  26755. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26756. groupStart += groupCount;
  26757. groupCount = 0;
  26758. }
  26759. }
  26760. // build geometry
  26761. this.setIndex( indices );
  26762. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26763. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26764. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26765. // helper functions
  26766. function addShape( shape ) {
  26767. const indexOffset = vertices.length / 3;
  26768. const points = shape.extractPoints( curveSegments );
  26769. let shapeVertices = points.shape;
  26770. const shapeHoles = points.holes;
  26771. // check direction of vertices
  26772. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26773. shapeVertices = shapeVertices.reverse();
  26774. }
  26775. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26776. const shapeHole = shapeHoles[ i ];
  26777. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26778. shapeHoles[ i ] = shapeHole.reverse();
  26779. }
  26780. }
  26781. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26782. // join vertices of inner and outer paths to a single array
  26783. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26784. const shapeHole = shapeHoles[ i ];
  26785. shapeVertices = shapeVertices.concat( shapeHole );
  26786. }
  26787. // vertices, normals, uvs
  26788. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26789. const vertex = shapeVertices[ i ];
  26790. vertices.push( vertex.x, vertex.y, 0 );
  26791. normals.push( 0, 0, 1 );
  26792. uvs.push( vertex.x, vertex.y ); // world uvs
  26793. }
  26794. // indices
  26795. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26796. const face = faces[ i ];
  26797. const a = face[ 0 ] + indexOffset;
  26798. const b = face[ 1 ] + indexOffset;
  26799. const c = face[ 2 ] + indexOffset;
  26800. indices.push( a, b, c );
  26801. groupCount += 3;
  26802. }
  26803. }
  26804. }
  26805. copy( source ) {
  26806. super.copy( source );
  26807. this.parameters = Object.assign( {}, source.parameters );
  26808. return this;
  26809. }
  26810. toJSON() {
  26811. const data = super.toJSON();
  26812. const shapes = this.parameters.shapes;
  26813. return toJSON( shapes, data );
  26814. }
  26815. /**
  26816. * Factory method for creating an instance of this class from the given
  26817. * JSON object.
  26818. *
  26819. * @param {Object} data - A JSON object representing the serialized geometry.
  26820. * @param {Array<Shape>} shapes - An array of shapes.
  26821. * @return {ShapeGeometry} A new instance.
  26822. */
  26823. static fromJSON( data, shapes ) {
  26824. const geometryShapes = [];
  26825. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26826. const shape = shapes[ data.shapes[ j ] ];
  26827. geometryShapes.push( shape );
  26828. }
  26829. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26830. }
  26831. }
  26832. function toJSON( shapes, data ) {
  26833. data.shapes = [];
  26834. if ( Array.isArray( shapes ) ) {
  26835. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26836. const shape = shapes[ i ];
  26837. data.shapes.push( shape.uuid );
  26838. }
  26839. } else {
  26840. data.shapes.push( shapes.uuid );
  26841. }
  26842. return data;
  26843. }
  26844. /**
  26845. * A class for generating a sphere geometry.
  26846. *
  26847. * ```js
  26848. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26849. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26850. * const sphere = new THREE.Mesh( geometry, material );
  26851. * scene.add( sphere );
  26852. * ```
  26853. *
  26854. * @augments BufferGeometry
  26855. */
  26856. class SphereGeometry extends BufferGeometry {
  26857. /**
  26858. * Constructs a new sphere geometry.
  26859. *
  26860. * @param {number} [radius=1] - The sphere radius.
  26861. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26862. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26863. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26864. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26865. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26866. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26867. */
  26868. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26869. super();
  26870. this.type = 'SphereGeometry';
  26871. /**
  26872. * Holds the constructor parameters that have been
  26873. * used to generate the geometry. Any modification
  26874. * after instantiation does not change the geometry.
  26875. *
  26876. * @type {Object}
  26877. */
  26878. this.parameters = {
  26879. radius: radius,
  26880. widthSegments: widthSegments,
  26881. heightSegments: heightSegments,
  26882. phiStart: phiStart,
  26883. phiLength: phiLength,
  26884. thetaStart: thetaStart,
  26885. thetaLength: thetaLength
  26886. };
  26887. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26888. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26889. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26890. let index = 0;
  26891. const grid = [];
  26892. const vertex = new Vector3();
  26893. const normal = new Vector3();
  26894. // buffers
  26895. const indices = [];
  26896. const vertices = [];
  26897. const normals = [];
  26898. const uvs = [];
  26899. // generate vertices, normals and uvs
  26900. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26901. const verticesRow = [];
  26902. const v = iy / heightSegments;
  26903. // special case for the poles
  26904. let uOffset = 0;
  26905. if ( iy === 0 && thetaStart === 0 ) {
  26906. uOffset = 0.5 / widthSegments;
  26907. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26908. uOffset = -0.5 / widthSegments;
  26909. }
  26910. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26911. const u = ix / widthSegments;
  26912. // vertex
  26913. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26914. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26915. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26916. vertices.push( vertex.x, vertex.y, vertex.z );
  26917. // normal
  26918. normal.copy( vertex ).normalize();
  26919. normals.push( normal.x, normal.y, normal.z );
  26920. // uv
  26921. uvs.push( u + uOffset, 1 - v );
  26922. verticesRow.push( index ++ );
  26923. }
  26924. grid.push( verticesRow );
  26925. }
  26926. // indices
  26927. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26928. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26929. const a = grid[ iy ][ ix + 1 ];
  26930. const b = grid[ iy ][ ix ];
  26931. const c = grid[ iy + 1 ][ ix ];
  26932. const d = grid[ iy + 1 ][ ix + 1 ];
  26933. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26934. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26935. }
  26936. }
  26937. // build geometry
  26938. this.setIndex( indices );
  26939. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26940. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26941. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26942. }
  26943. copy( source ) {
  26944. super.copy( source );
  26945. this.parameters = Object.assign( {}, source.parameters );
  26946. return this;
  26947. }
  26948. /**
  26949. * Factory method for creating an instance of this class from the given
  26950. * JSON object.
  26951. *
  26952. * @param {Object} data - A JSON object representing the serialized geometry.
  26953. * @return {SphereGeometry} A new instance.
  26954. */
  26955. static fromJSON( data ) {
  26956. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26957. }
  26958. }
  26959. /**
  26960. * A geometry class for representing an tetrahedron.
  26961. *
  26962. * ```js
  26963. * const geometry = new THREE.TetrahedronGeometry();
  26964. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26965. * const tetrahedron = new THREE.Mesh( geometry, material );
  26966. * scene.add( tetrahedron );
  26967. * ```
  26968. *
  26969. * @augments PolyhedronGeometry
  26970. */
  26971. class TetrahedronGeometry extends PolyhedronGeometry {
  26972. /**
  26973. * Constructs a new tetrahedron geometry.
  26974. *
  26975. * @param {number} [radius=1] - Radius of the tetrahedron.
  26976. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26977. */
  26978. constructor( radius = 1, detail = 0 ) {
  26979. const vertices = [
  26980. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26981. ];
  26982. const indices = [
  26983. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26984. ];
  26985. super( vertices, indices, radius, detail );
  26986. this.type = 'TetrahedronGeometry';
  26987. /**
  26988. * Holds the constructor parameters that have been
  26989. * used to generate the geometry. Any modification
  26990. * after instantiation does not change the geometry.
  26991. *
  26992. * @type {Object}
  26993. */
  26994. this.parameters = {
  26995. radius: radius,
  26996. detail: detail
  26997. };
  26998. }
  26999. /**
  27000. * Factory method for creating an instance of this class from the given
  27001. * JSON object.
  27002. *
  27003. * @param {Object} data - A JSON object representing the serialized geometry.
  27004. * @return {TetrahedronGeometry} A new instance.
  27005. */
  27006. static fromJSON( data ) {
  27007. return new TetrahedronGeometry( data.radius, data.detail );
  27008. }
  27009. }
  27010. /**
  27011. * A geometry class for representing an torus.
  27012. *
  27013. * ```js
  27014. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  27015. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27016. * const torus = new THREE.Mesh( geometry, material );
  27017. * scene.add( torus );
  27018. * ```
  27019. *
  27020. * @augments BufferGeometry
  27021. */
  27022. class TorusGeometry extends BufferGeometry {
  27023. /**
  27024. * Constructs a new torus geometry.
  27025. *
  27026. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  27027. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  27028. * @param {number} [radialSegments=12] - The number of radial segments.
  27029. * @param {number} [tubularSegments=48] - The number of tubular segments.
  27030. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  27031. */
  27032. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  27033. super();
  27034. this.type = 'TorusGeometry';
  27035. /**
  27036. * Holds the constructor parameters that have been
  27037. * used to generate the geometry. Any modification
  27038. * after instantiation does not change the geometry.
  27039. *
  27040. * @type {Object}
  27041. */
  27042. this.parameters = {
  27043. radius: radius,
  27044. tube: tube,
  27045. radialSegments: radialSegments,
  27046. tubularSegments: tubularSegments,
  27047. arc: arc
  27048. };
  27049. radialSegments = Math.floor( radialSegments );
  27050. tubularSegments = Math.floor( tubularSegments );
  27051. // buffers
  27052. const indices = [];
  27053. const vertices = [];
  27054. const normals = [];
  27055. const uvs = [];
  27056. // helper variables
  27057. const center = new Vector3();
  27058. const vertex = new Vector3();
  27059. const normal = new Vector3();
  27060. // generate vertices, normals and uvs
  27061. for ( let j = 0; j <= radialSegments; j ++ ) {
  27062. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27063. const u = i / tubularSegments * arc;
  27064. const v = j / radialSegments * Math.PI * 2;
  27065. // vertex
  27066. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27067. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27068. vertex.z = tube * Math.sin( v );
  27069. vertices.push( vertex.x, vertex.y, vertex.z );
  27070. // normal
  27071. center.x = radius * Math.cos( u );
  27072. center.y = radius * Math.sin( u );
  27073. normal.subVectors( vertex, center ).normalize();
  27074. normals.push( normal.x, normal.y, normal.z );
  27075. // uv
  27076. uvs.push( i / tubularSegments );
  27077. uvs.push( j / radialSegments );
  27078. }
  27079. }
  27080. // generate indices
  27081. for ( let j = 1; j <= radialSegments; j ++ ) {
  27082. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27083. // indices
  27084. const a = ( tubularSegments + 1 ) * j + i - 1;
  27085. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27086. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27087. const d = ( tubularSegments + 1 ) * j + i;
  27088. // faces
  27089. indices.push( a, b, d );
  27090. indices.push( b, c, d );
  27091. }
  27092. }
  27093. // build geometry
  27094. this.setIndex( indices );
  27095. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27096. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27097. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27098. }
  27099. copy( source ) {
  27100. super.copy( source );
  27101. this.parameters = Object.assign( {}, source.parameters );
  27102. return this;
  27103. }
  27104. /**
  27105. * Factory method for creating an instance of this class from the given
  27106. * JSON object.
  27107. *
  27108. * @param {Object} data - A JSON object representing the serialized geometry.
  27109. * @return {TorusGeometry} A new instance.
  27110. */
  27111. static fromJSON( data ) {
  27112. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27113. }
  27114. }
  27115. /**
  27116. * Creates a torus knot, the particular shape of which is defined by a pair
  27117. * of coprime integers, p and q. If p and q are not coprime, the result will
  27118. * be a torus link.
  27119. *
  27120. * ```js
  27121. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27122. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27123. * const torusKnot = new THREE.Mesh( geometry, material );
  27124. * scene.add( torusKnot );
  27125. * ```
  27126. *
  27127. * @augments BufferGeometry
  27128. */
  27129. class TorusKnotGeometry extends BufferGeometry {
  27130. /**
  27131. * Constructs a new torus knot geometry.
  27132. *
  27133. * @param {number} [radius=1] - Radius of the torus knot.
  27134. * @param {number} [tube=0.4] - Radius of the tube.
  27135. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27136. * @param {number} [radialSegments=8] - The number of radial segments.
  27137. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27138. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27139. */
  27140. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27141. super();
  27142. this.type = 'TorusKnotGeometry';
  27143. /**
  27144. * Holds the constructor parameters that have been
  27145. * used to generate the geometry. Any modification
  27146. * after instantiation does not change the geometry.
  27147. *
  27148. * @type {Object}
  27149. */
  27150. this.parameters = {
  27151. radius: radius,
  27152. tube: tube,
  27153. tubularSegments: tubularSegments,
  27154. radialSegments: radialSegments,
  27155. p: p,
  27156. q: q
  27157. };
  27158. tubularSegments = Math.floor( tubularSegments );
  27159. radialSegments = Math.floor( radialSegments );
  27160. // buffers
  27161. const indices = [];
  27162. const vertices = [];
  27163. const normals = [];
  27164. const uvs = [];
  27165. // helper variables
  27166. const vertex = new Vector3();
  27167. const normal = new Vector3();
  27168. const P1 = new Vector3();
  27169. const P2 = new Vector3();
  27170. const B = new Vector3();
  27171. const T = new Vector3();
  27172. const N = new Vector3();
  27173. // generate vertices, normals and uvs
  27174. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27175. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27176. const u = i / tubularSegments * p * Math.PI * 2;
  27177. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27178. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27179. calculatePositionOnCurve( u, p, q, radius, P1 );
  27180. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27181. // calculate orthonormal basis
  27182. T.subVectors( P2, P1 );
  27183. N.addVectors( P2, P1 );
  27184. B.crossVectors( T, N );
  27185. N.crossVectors( B, T );
  27186. // normalize B, N. T can be ignored, we don't use it
  27187. B.normalize();
  27188. N.normalize();
  27189. for ( let j = 0; j <= radialSegments; ++ j ) {
  27190. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27191. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27192. const v = j / radialSegments * Math.PI * 2;
  27193. const cx = - tube * Math.cos( v );
  27194. const cy = tube * Math.sin( v );
  27195. // now calculate the final vertex position.
  27196. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27197. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27198. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27199. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27200. vertices.push( vertex.x, vertex.y, vertex.z );
  27201. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27202. normal.subVectors( vertex, P1 ).normalize();
  27203. normals.push( normal.x, normal.y, normal.z );
  27204. // uv
  27205. uvs.push( i / tubularSegments );
  27206. uvs.push( j / radialSegments );
  27207. }
  27208. }
  27209. // generate indices
  27210. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27211. for ( let i = 1; i <= radialSegments; i ++ ) {
  27212. // indices
  27213. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27214. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27215. const c = ( radialSegments + 1 ) * j + i;
  27216. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27217. // faces
  27218. indices.push( a, b, d );
  27219. indices.push( b, c, d );
  27220. }
  27221. }
  27222. // build geometry
  27223. this.setIndex( indices );
  27224. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27225. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27226. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27227. // this function calculates the current position on the torus curve
  27228. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27229. const cu = Math.cos( u );
  27230. const su = Math.sin( u );
  27231. const quOverP = q / p * u;
  27232. const cs = Math.cos( quOverP );
  27233. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27234. position.y = radius * ( 2 + cs ) * su * 0.5;
  27235. position.z = radius * Math.sin( quOverP ) * 0.5;
  27236. }
  27237. }
  27238. copy( source ) {
  27239. super.copy( source );
  27240. this.parameters = Object.assign( {}, source.parameters );
  27241. return this;
  27242. }
  27243. /**
  27244. * Factory method for creating an instance of this class from the given
  27245. * JSON object.
  27246. *
  27247. * @param {Object} data - A JSON object representing the serialized geometry.
  27248. * @return {TorusKnotGeometry} A new instance.
  27249. */
  27250. static fromJSON( data ) {
  27251. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27252. }
  27253. }
  27254. /**
  27255. * Creates a tube that extrudes along a 3D curve.
  27256. *
  27257. * ```js
  27258. * class CustomSinCurve extends THREE.Curve {
  27259. *
  27260. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27261. *
  27262. * const tx = t * 3 - 1.5;
  27263. * const ty = Math.sin( 2 * Math.PI * t );
  27264. * const tz = 0;
  27265. *
  27266. * return optionalTarget.set( tx, ty, tz );
  27267. * }
  27268. *
  27269. * }
  27270. *
  27271. * const path = new CustomSinCurve( 10 );
  27272. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27273. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27274. * const mesh = new THREE.Mesh( geometry, material );
  27275. * scene.add( mesh );
  27276. * ```
  27277. *
  27278. * @augments BufferGeometry
  27279. */
  27280. class TubeGeometry extends BufferGeometry {
  27281. /**
  27282. * Constructs a new tube geometry.
  27283. *
  27284. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27285. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27286. * @param {number} [radius=1] -The radius of the tube.
  27287. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27288. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27289. */
  27290. 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 ) {
  27291. super();
  27292. this.type = 'TubeGeometry';
  27293. /**
  27294. * Holds the constructor parameters that have been
  27295. * used to generate the geometry. Any modification
  27296. * after instantiation does not change the geometry.
  27297. *
  27298. * @type {Object}
  27299. */
  27300. this.parameters = {
  27301. path: path,
  27302. tubularSegments: tubularSegments,
  27303. radius: radius,
  27304. radialSegments: radialSegments,
  27305. closed: closed
  27306. };
  27307. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27308. // expose internals
  27309. this.tangents = frames.tangents;
  27310. this.normals = frames.normals;
  27311. this.binormals = frames.binormals;
  27312. // helper variables
  27313. const vertex = new Vector3();
  27314. const normal = new Vector3();
  27315. const uv = new Vector2();
  27316. let P = new Vector3();
  27317. // buffer
  27318. const vertices = [];
  27319. const normals = [];
  27320. const uvs = [];
  27321. const indices = [];
  27322. // create buffer data
  27323. generateBufferData();
  27324. // build geometry
  27325. this.setIndex( indices );
  27326. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27327. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27328. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27329. // functions
  27330. function generateBufferData() {
  27331. for ( let i = 0; i < tubularSegments; i ++ ) {
  27332. generateSegment( i );
  27333. }
  27334. // if the geometry is not closed, generate the last row of vertices and normals
  27335. // at the regular position on the given path
  27336. //
  27337. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27338. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27339. // uvs are generated in a separate function.
  27340. // this makes it easy compute correct values for closed geometries
  27341. generateUVs();
  27342. // finally create faces
  27343. generateIndices();
  27344. }
  27345. function generateSegment( i ) {
  27346. // we use getPointAt to sample evenly distributed points from the given path
  27347. P = path.getPointAt( i / tubularSegments, P );
  27348. // retrieve corresponding normal and binormal
  27349. const N = frames.normals[ i ];
  27350. const B = frames.binormals[ i ];
  27351. // generate normals and vertices for the current segment
  27352. for ( let j = 0; j <= radialSegments; j ++ ) {
  27353. const v = j / radialSegments * Math.PI * 2;
  27354. const sin = Math.sin( v );
  27355. const cos = - Math.cos( v );
  27356. // normal
  27357. normal.x = ( cos * N.x + sin * B.x );
  27358. normal.y = ( cos * N.y + sin * B.y );
  27359. normal.z = ( cos * N.z + sin * B.z );
  27360. normal.normalize();
  27361. normals.push( normal.x, normal.y, normal.z );
  27362. // vertex
  27363. vertex.x = P.x + radius * normal.x;
  27364. vertex.y = P.y + radius * normal.y;
  27365. vertex.z = P.z + radius * normal.z;
  27366. vertices.push( vertex.x, vertex.y, vertex.z );
  27367. }
  27368. }
  27369. function generateIndices() {
  27370. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27371. for ( let i = 1; i <= radialSegments; i ++ ) {
  27372. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27373. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27374. const c = ( radialSegments + 1 ) * j + i;
  27375. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27376. // faces
  27377. indices.push( a, b, d );
  27378. indices.push( b, c, d );
  27379. }
  27380. }
  27381. }
  27382. function generateUVs() {
  27383. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27384. for ( let j = 0; j <= radialSegments; j ++ ) {
  27385. uv.x = i / tubularSegments;
  27386. uv.y = j / radialSegments;
  27387. uvs.push( uv.x, uv.y );
  27388. }
  27389. }
  27390. }
  27391. }
  27392. copy( source ) {
  27393. super.copy( source );
  27394. this.parameters = Object.assign( {}, source.parameters );
  27395. return this;
  27396. }
  27397. toJSON() {
  27398. const data = super.toJSON();
  27399. data.path = this.parameters.path.toJSON();
  27400. return data;
  27401. }
  27402. /**
  27403. * Factory method for creating an instance of this class from the given
  27404. * JSON object.
  27405. *
  27406. * @param {Object} data - A JSON object representing the serialized geometry.
  27407. * @return {TubeGeometry} A new instance.
  27408. */
  27409. static fromJSON( data ) {
  27410. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27411. // User defined curves or instances of CurvePath will not be deserialized.
  27412. return new TubeGeometry(
  27413. new Curves[ data.path.type ]().fromJSON( data.path ),
  27414. data.tubularSegments,
  27415. data.radius,
  27416. data.radialSegments,
  27417. data.closed
  27418. );
  27419. }
  27420. }
  27421. /**
  27422. * Can be used as a helper object to visualize a geometry as a wireframe.
  27423. *
  27424. * ```js
  27425. * const geometry = new THREE.SphereGeometry();
  27426. *
  27427. * const wireframe = new THREE.WireframeGeometry( geometry );
  27428. *
  27429. * const line = new THREE.LineSegments( wireframe );
  27430. * line.material.depthWrite = false;
  27431. * line.material.opacity = 0.25;
  27432. * line.material.transparent = true;
  27433. *
  27434. * scene.add( line );
  27435. * ```
  27436. *
  27437. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27438. *
  27439. * @augments BufferGeometry
  27440. */
  27441. class WireframeGeometry extends BufferGeometry {
  27442. /**
  27443. * Constructs a new wireframe geometry.
  27444. *
  27445. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27446. */
  27447. constructor( geometry = null ) {
  27448. super();
  27449. this.type = 'WireframeGeometry';
  27450. /**
  27451. * Holds the constructor parameters that have been
  27452. * used to generate the geometry. Any modification
  27453. * after instantiation does not change the geometry.
  27454. *
  27455. * @type {Object}
  27456. */
  27457. this.parameters = {
  27458. geometry: geometry
  27459. };
  27460. if ( geometry !== null ) {
  27461. // buffer
  27462. const vertices = [];
  27463. const edges = new Set();
  27464. // helper variables
  27465. const start = new Vector3();
  27466. const end = new Vector3();
  27467. if ( geometry.index !== null ) {
  27468. // indexed BufferGeometry
  27469. const position = geometry.attributes.position;
  27470. const indices = geometry.index;
  27471. let groups = geometry.groups;
  27472. if ( groups.length === 0 ) {
  27473. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27474. }
  27475. // create a data structure that contains all edges without duplicates
  27476. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27477. const group = groups[ o ];
  27478. const groupStart = group.start;
  27479. const groupCount = group.count;
  27480. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27481. for ( let j = 0; j < 3; j ++ ) {
  27482. const index1 = indices.getX( i + j );
  27483. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27484. start.fromBufferAttribute( position, index1 );
  27485. end.fromBufferAttribute( position, index2 );
  27486. if ( isUniqueEdge( start, end, edges ) === true ) {
  27487. vertices.push( start.x, start.y, start.z );
  27488. vertices.push( end.x, end.y, end.z );
  27489. }
  27490. }
  27491. }
  27492. }
  27493. } else {
  27494. // non-indexed BufferGeometry
  27495. const position = geometry.attributes.position;
  27496. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27497. for ( let j = 0; j < 3; j ++ ) {
  27498. // three edges per triangle, an edge is represented as (index1, index2)
  27499. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27500. const index1 = 3 * i + j;
  27501. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27502. start.fromBufferAttribute( position, index1 );
  27503. end.fromBufferAttribute( position, index2 );
  27504. if ( isUniqueEdge( start, end, edges ) === true ) {
  27505. vertices.push( start.x, start.y, start.z );
  27506. vertices.push( end.x, end.y, end.z );
  27507. }
  27508. }
  27509. }
  27510. }
  27511. // build geometry
  27512. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27513. }
  27514. }
  27515. copy( source ) {
  27516. super.copy( source );
  27517. this.parameters = Object.assign( {}, source.parameters );
  27518. return this;
  27519. }
  27520. }
  27521. function isUniqueEdge( start, end, edges ) {
  27522. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27523. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27524. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27525. return false;
  27526. } else {
  27527. edges.add( hash1 );
  27528. edges.add( hash2 );
  27529. return true;
  27530. }
  27531. }
  27532. var Geometries = /*#__PURE__*/Object.freeze({
  27533. __proto__: null,
  27534. BoxGeometry: BoxGeometry,
  27535. CapsuleGeometry: CapsuleGeometry,
  27536. CircleGeometry: CircleGeometry,
  27537. ConeGeometry: ConeGeometry,
  27538. CylinderGeometry: CylinderGeometry,
  27539. DodecahedronGeometry: DodecahedronGeometry,
  27540. EdgesGeometry: EdgesGeometry,
  27541. ExtrudeGeometry: ExtrudeGeometry,
  27542. IcosahedronGeometry: IcosahedronGeometry,
  27543. LatheGeometry: LatheGeometry,
  27544. OctahedronGeometry: OctahedronGeometry,
  27545. PlaneGeometry: PlaneGeometry,
  27546. PolyhedronGeometry: PolyhedronGeometry,
  27547. RingGeometry: RingGeometry,
  27548. ShapeGeometry: ShapeGeometry,
  27549. SphereGeometry: SphereGeometry,
  27550. TetrahedronGeometry: TetrahedronGeometry,
  27551. TorusGeometry: TorusGeometry,
  27552. TorusKnotGeometry: TorusKnotGeometry,
  27553. TubeGeometry: TubeGeometry,
  27554. WireframeGeometry: WireframeGeometry
  27555. });
  27556. /**
  27557. * This material can receive shadows, but otherwise is completely transparent.
  27558. *
  27559. * ```js
  27560. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27561. * geometry.rotateX( - Math.PI / 2 );
  27562. *
  27563. * const material = new THREE.ShadowMaterial();
  27564. * material.opacity = 0.2;
  27565. *
  27566. * const plane = new THREE.Mesh( geometry, material );
  27567. * plane.position.y = -200;
  27568. * plane.receiveShadow = true;
  27569. * scene.add( plane );
  27570. * ```
  27571. *
  27572. * @augments Material
  27573. */
  27574. class ShadowMaterial extends Material {
  27575. /**
  27576. * Constructs a new shadow material.
  27577. *
  27578. * @param {Object} [parameters] - An object with one or more properties
  27579. * defining the material's appearance. Any property of the material
  27580. * (including any property from inherited materials) can be passed
  27581. * in here. Color values can be passed any type of value accepted
  27582. * by {@link Color#set}.
  27583. */
  27584. constructor( parameters ) {
  27585. super();
  27586. /**
  27587. * This flag can be used for type testing.
  27588. *
  27589. * @type {boolean}
  27590. * @readonly
  27591. * @default true
  27592. */
  27593. this.isShadowMaterial = true;
  27594. this.type = 'ShadowMaterial';
  27595. /**
  27596. * Color of the material.
  27597. *
  27598. * @type {Color}
  27599. * @default (0,0,0)
  27600. */
  27601. this.color = new Color( 0x000000 );
  27602. /**
  27603. * Overwritten since shadow materials are transparent
  27604. * by default.
  27605. *
  27606. * @type {boolean}
  27607. * @default true
  27608. */
  27609. this.transparent = true;
  27610. /**
  27611. * Whether the material is affected by fog or not.
  27612. *
  27613. * @type {boolean}
  27614. * @default true
  27615. */
  27616. this.fog = true;
  27617. this.setValues( parameters );
  27618. }
  27619. copy( source ) {
  27620. super.copy( source );
  27621. this.color.copy( source.color );
  27622. this.fog = source.fog;
  27623. return this;
  27624. }
  27625. }
  27626. /**
  27627. * This class works just like {@link ShaderMaterial}, except that definitions
  27628. * of built-in uniforms and attributes are not automatically prepended to the
  27629. * GLSL shader code.
  27630. *
  27631. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27632. *
  27633. * @augments ShaderMaterial
  27634. */
  27635. class RawShaderMaterial extends ShaderMaterial {
  27636. /**
  27637. * Constructs a new raw shader material.
  27638. *
  27639. * @param {Object} [parameters] - An object with one or more properties
  27640. * defining the material's appearance. Any property of the material
  27641. * (including any property from inherited materials) can be passed
  27642. * in here. Color values can be passed any type of value accepted
  27643. * by {@link Color#set}.
  27644. */
  27645. constructor( parameters ) {
  27646. super( parameters );
  27647. /**
  27648. * This flag can be used for type testing.
  27649. *
  27650. * @type {boolean}
  27651. * @readonly
  27652. * @default true
  27653. */
  27654. this.isRawShaderMaterial = true;
  27655. this.type = 'RawShaderMaterial';
  27656. }
  27657. }
  27658. /**
  27659. * A standard physically based material, using Metallic-Roughness workflow.
  27660. *
  27661. * Physically based rendering (PBR) has recently become the standard in many
  27662. * 3D applications, such as [Unity]{@link https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/},
  27663. * [Unreal]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/} and
  27664. * [3D Studio Max]{@link http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017}.
  27665. *
  27666. * This approach differs from older approaches in that instead of using
  27667. * approximations for the way in which light interacts with a surface, a
  27668. * physically correct model is used. The idea is that, instead of tweaking
  27669. * materials to look good under specific lighting, a material can be created
  27670. * that will react 'correctly' under all lighting scenarios.
  27671. *
  27672. * In practice this gives a more accurate and realistic looking result than
  27673. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27674. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27675. * shading.
  27676. *
  27677. * Note that for best results you should always specify an environment map when using this material.
  27678. *
  27679. * For a non-technical introduction to the concept of PBR and how to set up a
  27680. * PBR material, check out these articles by the people at [marmoset]{@link https://www.marmoset.co}:
  27681. *
  27682. * - [Basic Theory of Physically Based Rendering]{@link https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/}
  27683. * - [Physically Based Rendering and You Can Too]{@link https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/}
  27684. *
  27685. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27686. * [paper from Disney]{@link https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf}
  27687. * (pdf), by Brent Burley.
  27688. *
  27689. * @augments Material
  27690. */
  27691. class MeshStandardMaterial extends Material {
  27692. /**
  27693. * Constructs a new mesh standard material.
  27694. *
  27695. * @param {Object} [parameters] - An object with one or more properties
  27696. * defining the material's appearance. Any property of the material
  27697. * (including any property from inherited materials) can be passed
  27698. * in here. Color values can be passed any type of value accepted
  27699. * by {@link Color#set}.
  27700. */
  27701. constructor( parameters ) {
  27702. super();
  27703. /**
  27704. * This flag can be used for type testing.
  27705. *
  27706. * @type {boolean}
  27707. * @readonly
  27708. * @default true
  27709. */
  27710. this.isMeshStandardMaterial = true;
  27711. this.type = 'MeshStandardMaterial';
  27712. this.defines = { 'STANDARD': '' };
  27713. /**
  27714. * Color of the material.
  27715. *
  27716. * @type {Color}
  27717. * @default (1,1,1)
  27718. */
  27719. this.color = new Color( 0xffffff ); // diffuse
  27720. /**
  27721. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27722. * means fully diffuse. If `roughnessMap` is also provided,
  27723. * both values are multiplied.
  27724. *
  27725. * @type {number}
  27726. * @default 1
  27727. */
  27728. this.roughness = 1.0;
  27729. /**
  27730. * How much the material is like a metal. Non-metallic materials such as wood
  27731. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27732. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27733. * If `metalnessMap` is also provided, both values are multiplied.
  27734. *
  27735. * @type {number}
  27736. * @default 0
  27737. */
  27738. this.metalness = 0.0;
  27739. /**
  27740. * The color map. May optionally include an alpha channel, typically combined
  27741. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27742. * color is modulated by the diffuse `color`.
  27743. *
  27744. * @type {?Texture}
  27745. * @default null
  27746. */
  27747. this.map = null;
  27748. /**
  27749. * The light map. Requires a second set of UVs.
  27750. *
  27751. * @type {?Texture}
  27752. * @default null
  27753. */
  27754. this.lightMap = null;
  27755. /**
  27756. * Intensity of the baked light.
  27757. *
  27758. * @type {number}
  27759. * @default 1
  27760. */
  27761. this.lightMapIntensity = 1.0;
  27762. /**
  27763. * The red channel of this texture is used as the ambient occlusion map.
  27764. * Requires a second set of UVs.
  27765. *
  27766. * @type {?Texture}
  27767. * @default null
  27768. */
  27769. this.aoMap = null;
  27770. /**
  27771. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27772. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27773. * red channel is also `1`, ambient light is fully occluded on a surface.
  27774. *
  27775. * @type {number}
  27776. * @default 1
  27777. */
  27778. this.aoMapIntensity = 1.0;
  27779. /**
  27780. * Emissive (light) color of the material, essentially a solid color
  27781. * unaffected by other lighting.
  27782. *
  27783. * @type {Color}
  27784. * @default (0,0,0)
  27785. */
  27786. this.emissive = new Color( 0x000000 );
  27787. /**
  27788. * Intensity of the emissive light. Modulates the emissive color.
  27789. *
  27790. * @type {number}
  27791. * @default 1
  27792. */
  27793. this.emissiveIntensity = 1.0;
  27794. /**
  27795. * Set emissive (glow) map. The emissive map color is modulated by the
  27796. * emissive color and the emissive intensity. If you have an emissive map,
  27797. * be sure to set the emissive color to something other than black.
  27798. *
  27799. * @type {?Texture}
  27800. * @default null
  27801. */
  27802. this.emissiveMap = null;
  27803. /**
  27804. * The texture to create a bump map. The black and white values map to the
  27805. * perceived depth in relation to the lights. Bump doesn't actually affect
  27806. * the geometry of the object, only the lighting. If a normal map is defined
  27807. * this will be ignored.
  27808. *
  27809. * @type {?Texture}
  27810. * @default null
  27811. */
  27812. this.bumpMap = null;
  27813. /**
  27814. * How much the bump map affects the material. Typical range is `[0,1]`.
  27815. *
  27816. * @type {number}
  27817. * @default 1
  27818. */
  27819. this.bumpScale = 1;
  27820. /**
  27821. * The texture to create a normal map. The RGB values affect the surface
  27822. * normal for each pixel fragment and change the way the color is lit. Normal
  27823. * maps do not change the actual shape of the surface, only the lighting. In
  27824. * case the material has a normal map authored using the left handed
  27825. * convention, the `y` component of `normalScale` should be negated to compensate
  27826. * for the different handedness.
  27827. *
  27828. * @type {?Texture}
  27829. * @default null
  27830. */
  27831. this.normalMap = null;
  27832. /**
  27833. * The type of normal map.
  27834. *
  27835. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27836. * @default TangentSpaceNormalMap
  27837. */
  27838. this.normalMapType = TangentSpaceNormalMap;
  27839. /**
  27840. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27841. *
  27842. * @type {Vector2}
  27843. * @default (1,1)
  27844. */
  27845. this.normalScale = new Vector2( 1, 1 );
  27846. /**
  27847. * The displacement map affects the position of the mesh's vertices. Unlike
  27848. * other maps which only affect the light and shade of the material the
  27849. * displaced vertices can cast shadows, block other objects, and otherwise
  27850. * act as real geometry. The displacement texture is an image where the value
  27851. * of each pixel (white being the highest) is mapped against, and
  27852. * repositions, the vertices of the mesh.
  27853. *
  27854. * @type {?Texture}
  27855. * @default null
  27856. */
  27857. this.displacementMap = null;
  27858. /**
  27859. * How much the displacement map affects the mesh (where black is no
  27860. * displacement, and white is maximum displacement). Without a displacement
  27861. * map set, this value is not applied.
  27862. *
  27863. * @type {number}
  27864. * @default 0
  27865. */
  27866. this.displacementScale = 1;
  27867. /**
  27868. * The offset of the displacement map's values on the mesh's vertices.
  27869. * The bias is added to the scaled sample of the displacement map.
  27870. * Without a displacement map set, this value is not applied.
  27871. *
  27872. * @type {number}
  27873. * @default 0
  27874. */
  27875. this.displacementBias = 0;
  27876. /**
  27877. * The green channel of this texture is used to alter the roughness of the
  27878. * material.
  27879. *
  27880. * @type {?Texture}
  27881. * @default null
  27882. */
  27883. this.roughnessMap = null;
  27884. /**
  27885. * The blue channel of this texture is used to alter the metalness of the
  27886. * material.
  27887. *
  27888. * @type {?Texture}
  27889. * @default null
  27890. */
  27891. this.metalnessMap = null;
  27892. /**
  27893. * The alpha map is a grayscale texture that controls the opacity across the
  27894. * surface (black: fully transparent; white: fully opaque).
  27895. *
  27896. * Only the color of the texture is used, ignoring the alpha channel if one
  27897. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27898. * when sampling this texture due to the extra bit of precision provided for
  27899. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27900. * luminance/alpha textures will also still work as expected.
  27901. *
  27902. * @type {?Texture}
  27903. * @default null
  27904. */
  27905. this.alphaMap = null;
  27906. /**
  27907. * The environment map. To ensure a physically correct rendering, environment maps
  27908. * are internally pre-processed with {@link PMREMGenerator}.
  27909. *
  27910. * @type {?Texture}
  27911. * @default null
  27912. */
  27913. this.envMap = null;
  27914. /**
  27915. * The rotation of the environment map in radians.
  27916. *
  27917. * @type {Euler}
  27918. * @default (0,0,0)
  27919. */
  27920. this.envMapRotation = new Euler();
  27921. /**
  27922. * Scales the effect of the environment map by multiplying its color.
  27923. *
  27924. * @type {number}
  27925. * @default 1
  27926. */
  27927. this.envMapIntensity = 1.0;
  27928. /**
  27929. * Renders the geometry as a wireframe.
  27930. *
  27931. * @type {boolean}
  27932. * @default false
  27933. */
  27934. this.wireframe = false;
  27935. /**
  27936. * Controls the thickness of the wireframe.
  27937. *
  27938. * Can only be used with {@link SVGRenderer}.
  27939. *
  27940. * @type {number}
  27941. * @default 1
  27942. */
  27943. this.wireframeLinewidth = 1;
  27944. /**
  27945. * Defines appearance of wireframe ends.
  27946. *
  27947. * Can only be used with {@link SVGRenderer}.
  27948. *
  27949. * @type {('round'|'bevel'|'miter')}
  27950. * @default 'round'
  27951. */
  27952. this.wireframeLinecap = 'round';
  27953. /**
  27954. * Defines appearance of wireframe joints.
  27955. *
  27956. * Can only be used with {@link SVGRenderer}.
  27957. *
  27958. * @type {('round'|'bevel'|'miter')}
  27959. * @default 'round'
  27960. */
  27961. this.wireframeLinejoin = 'round';
  27962. /**
  27963. * Whether the material is rendered with flat shading or not.
  27964. *
  27965. * @type {boolean}
  27966. * @default false
  27967. */
  27968. this.flatShading = false;
  27969. /**
  27970. * Whether the material is affected by fog or not.
  27971. *
  27972. * @type {boolean}
  27973. * @default true
  27974. */
  27975. this.fog = true;
  27976. this.setValues( parameters );
  27977. }
  27978. copy( source ) {
  27979. super.copy( source );
  27980. this.defines = { 'STANDARD': '' };
  27981. this.color.copy( source.color );
  27982. this.roughness = source.roughness;
  27983. this.metalness = source.metalness;
  27984. this.map = source.map;
  27985. this.lightMap = source.lightMap;
  27986. this.lightMapIntensity = source.lightMapIntensity;
  27987. this.aoMap = source.aoMap;
  27988. this.aoMapIntensity = source.aoMapIntensity;
  27989. this.emissive.copy( source.emissive );
  27990. this.emissiveMap = source.emissiveMap;
  27991. this.emissiveIntensity = source.emissiveIntensity;
  27992. this.bumpMap = source.bumpMap;
  27993. this.bumpScale = source.bumpScale;
  27994. this.normalMap = source.normalMap;
  27995. this.normalMapType = source.normalMapType;
  27996. this.normalScale.copy( source.normalScale );
  27997. this.displacementMap = source.displacementMap;
  27998. this.displacementScale = source.displacementScale;
  27999. this.displacementBias = source.displacementBias;
  28000. this.roughnessMap = source.roughnessMap;
  28001. this.metalnessMap = source.metalnessMap;
  28002. this.alphaMap = source.alphaMap;
  28003. this.envMap = source.envMap;
  28004. this.envMapRotation.copy( source.envMapRotation );
  28005. this.envMapIntensity = source.envMapIntensity;
  28006. this.wireframe = source.wireframe;
  28007. this.wireframeLinewidth = source.wireframeLinewidth;
  28008. this.wireframeLinecap = source.wireframeLinecap;
  28009. this.wireframeLinejoin = source.wireframeLinejoin;
  28010. this.flatShading = source.flatShading;
  28011. this.fog = source.fog;
  28012. return this;
  28013. }
  28014. }
  28015. /**
  28016. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28017. * physically-based rendering properties:
  28018. *
  28019. * - Anisotropy: Ability to represent the anisotropic property of materials
  28020. * as observable with brushed metals.
  28021. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28022. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28023. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28024. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28025. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28026. * wings of many insects.
  28027. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28028. * transparent materials are less reflective. Physically-based transmission provides a more
  28029. * realistic option for thin, transparent surfaces like glass.
  28030. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28031. * - Sheen: Can be used for representing cloth and fabric materials.
  28032. *
  28033. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28034. * higher performance cost, per pixel, than other three.js materials. Most
  28035. * effects are disabled by default, and add cost as they are enabled. For
  28036. * best results, always specify an environment map when using this material.
  28037. *
  28038. * @augments MeshStandardMaterial
  28039. */
  28040. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28041. /**
  28042. * Constructs a new mesh physical material.
  28043. *
  28044. * @param {Object} [parameters] - An object with one or more properties
  28045. * defining the material's appearance. Any property of the material
  28046. * (including any property from inherited materials) can be passed
  28047. * in here. Color values can be passed any type of value accepted
  28048. * by {@link Color#set}.
  28049. */
  28050. constructor( parameters ) {
  28051. super();
  28052. /**
  28053. * This flag can be used for type testing.
  28054. *
  28055. * @type {boolean}
  28056. * @readonly
  28057. * @default true
  28058. */
  28059. this.isMeshPhysicalMaterial = true;
  28060. this.defines = {
  28061. 'STANDARD': '',
  28062. 'PHYSICAL': ''
  28063. };
  28064. this.type = 'MeshPhysicalMaterial';
  28065. /**
  28066. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28067. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28068. * property provides additional rotation to the vectors in the texture.
  28069. *
  28070. * @type {number}
  28071. * @default 1
  28072. */
  28073. this.anisotropyRotation = 0;
  28074. /**
  28075. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28076. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28077. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28078. *
  28079. * @type {?Texture}
  28080. * @default null
  28081. */
  28082. this.anisotropyMap = null;
  28083. /**
  28084. * The red channel of this texture is multiplied against `clearcoat`,
  28085. * for per-pixel control over a coating's intensity.
  28086. *
  28087. * @type {?Texture}
  28088. * @default null
  28089. */
  28090. this.clearcoatMap = null;
  28091. /**
  28092. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28093. *
  28094. * @type {number}
  28095. * @default 0
  28096. */
  28097. this.clearcoatRoughness = 0.0;
  28098. /**
  28099. * The green channel of this texture is multiplied against
  28100. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28101. *
  28102. * @type {?Texture}
  28103. * @default null
  28104. */
  28105. this.clearcoatRoughnessMap = null;
  28106. /**
  28107. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28108. * `(0,0)` to `(1,1)`.
  28109. *
  28110. * @type {Vector2}
  28111. * @default (1,1)
  28112. */
  28113. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28114. /**
  28115. * Can be used to enable independent normals for the clear coat layer.
  28116. *
  28117. * @type {?Texture}
  28118. * @default null
  28119. */
  28120. this.clearcoatNormalMap = null;
  28121. /**
  28122. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28123. *
  28124. * @type {number}
  28125. * @default 1.5
  28126. */
  28127. this.ior = 1.5;
  28128. /**
  28129. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28130. * corresponds to an index-of-refraction of `1.5`.
  28131. *
  28132. * This models the reflectivity of non-metallic materials. It has no effect
  28133. * when `metalness` is `1.0`
  28134. *
  28135. * @name MeshPhysicalMaterial#reflectivity
  28136. * @type {number}
  28137. * @default 0.5
  28138. */
  28139. Object.defineProperty( this, 'reflectivity', {
  28140. get: function () {
  28141. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28142. },
  28143. set: function ( reflectivity ) {
  28144. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28145. }
  28146. } );
  28147. /**
  28148. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28149. * control over iridescence.
  28150. *
  28151. * @type {?Texture}
  28152. * @default null
  28153. */
  28154. this.iridescenceMap = null;
  28155. /**
  28156. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28157. * Between `1.0` to `2.333`.
  28158. *
  28159. * @type {number}
  28160. * @default 1.3
  28161. */
  28162. this.iridescenceIOR = 1.3;
  28163. /**
  28164. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28165. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28166. *
  28167. * @type {Array<number,number>}
  28168. * @default [100,400]
  28169. */
  28170. this.iridescenceThicknessRange = [ 100, 400 ];
  28171. /**
  28172. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28173. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28174. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28175. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28176. * - Values in-between will linearly interpolate between the elements of the array.
  28177. *
  28178. * @type {?Texture}
  28179. * @default null
  28180. */
  28181. this.iridescenceThicknessMap = null;
  28182. /**
  28183. * The sheen tint.
  28184. *
  28185. * @type {Color}
  28186. * @default (0,0,0)
  28187. */
  28188. this.sheenColor = new Color( 0x000000 );
  28189. /**
  28190. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28191. * over sheen tint.
  28192. *
  28193. * @type {?Texture}
  28194. * @default null
  28195. */
  28196. this.sheenColorMap = null;
  28197. /**
  28198. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28199. *
  28200. * @type {number}
  28201. * @default 1
  28202. */
  28203. this.sheenRoughness = 1.0;
  28204. /**
  28205. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28206. * over sheen roughness.
  28207. *
  28208. * @type {?Texture}
  28209. * @default null
  28210. */
  28211. this.sheenRoughnessMap = null;
  28212. /**
  28213. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28214. * optical transparency.
  28215. *
  28216. * @type {?Texture}
  28217. * @default null
  28218. */
  28219. this.transmissionMap = null;
  28220. /**
  28221. * The thickness of the volume beneath the surface. The value is given in the
  28222. * coordinate space of the mesh. If the value is `0` the material is
  28223. * thin-walled. Otherwise the material is a volume boundary.
  28224. *
  28225. * @type {number}
  28226. * @default 0
  28227. */
  28228. this.thickness = 0;
  28229. /**
  28230. * A texture that defines the thickness, stored in the green channel. This will
  28231. * be multiplied by `thickness`.
  28232. *
  28233. * @type {?Texture}
  28234. * @default null
  28235. */
  28236. this.thicknessMap = null;
  28237. /**
  28238. * Density of the medium given as the average distance that light travels in
  28239. * the medium before interacting with a particle. The value is given in world
  28240. * space units, and must be greater than zero.
  28241. *
  28242. * @type {number}
  28243. * @default Infinity
  28244. */
  28245. this.attenuationDistance = Infinity;
  28246. /**
  28247. * The color that white light turns into due to absorption when reaching the
  28248. * attenuation distance.
  28249. *
  28250. * @type {Color}
  28251. * @default (1,1,1)
  28252. */
  28253. this.attenuationColor = new Color( 1, 1, 1 );
  28254. /**
  28255. * A float that scales the amount of specular reflection for non-metals only.
  28256. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28257. *
  28258. * @type {number}
  28259. * @default 1
  28260. */
  28261. this.specularIntensity = 1.0;
  28262. /**
  28263. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28264. * for per-pixel control over specular intensity.
  28265. *
  28266. * @type {?Texture}
  28267. * @default null
  28268. */
  28269. this.specularIntensityMap = null;
  28270. /**
  28271. * Tints the specular reflection at normal incidence for non-metals only.
  28272. *
  28273. * @type {Color}
  28274. * @default (1,1,1)
  28275. */
  28276. this.specularColor = new Color( 1, 1, 1 );
  28277. /**
  28278. * The RGB channels of this texture are multiplied against `specularColor`,
  28279. * for per-pixel control over specular color.
  28280. *
  28281. * @type {?Texture}
  28282. * @default null
  28283. */
  28284. this.specularColorMap = null;
  28285. this._anisotropy = 0;
  28286. this._clearcoat = 0;
  28287. this._dispersion = 0;
  28288. this._iridescence = 0;
  28289. this._sheen = 0.0;
  28290. this._transmission = 0;
  28291. this.setValues( parameters );
  28292. }
  28293. /**
  28294. * The anisotropy strength.
  28295. *
  28296. * @type {number}
  28297. * @default 0
  28298. */
  28299. get anisotropy() {
  28300. return this._anisotropy;
  28301. }
  28302. set anisotropy( value ) {
  28303. if ( this._anisotropy > 0 !== value > 0 ) {
  28304. this.version ++;
  28305. }
  28306. this._anisotropy = value;
  28307. }
  28308. /**
  28309. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28310. * clear coat related properties to enable multilayer materials that have a
  28311. * thin translucent layer over the base layer.
  28312. *
  28313. * @type {number}
  28314. * @default 0
  28315. */
  28316. get clearcoat() {
  28317. return this._clearcoat;
  28318. }
  28319. set clearcoat( value ) {
  28320. if ( this._clearcoat > 0 !== value > 0 ) {
  28321. this.version ++;
  28322. }
  28323. this._clearcoat = value;
  28324. }
  28325. /**
  28326. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28327. * the surface and the viewer, from `0.0` to `1.0`.
  28328. *
  28329. * @type {number}
  28330. * @default 0
  28331. */
  28332. get iridescence() {
  28333. return this._iridescence;
  28334. }
  28335. set iridescence( value ) {
  28336. if ( this._iridescence > 0 !== value > 0 ) {
  28337. this.version ++;
  28338. }
  28339. this._iridescence = value;
  28340. }
  28341. /**
  28342. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28343. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28344. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28345. *
  28346. * @type {number}
  28347. * @default 0
  28348. */
  28349. get dispersion() {
  28350. return this._dispersion;
  28351. }
  28352. set dispersion( value ) {
  28353. if ( this._dispersion > 0 !== value > 0 ) {
  28354. this.version ++;
  28355. }
  28356. this._dispersion = value;
  28357. }
  28358. /**
  28359. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28360. *
  28361. * @type {number}
  28362. * @default 0
  28363. */
  28364. get sheen() {
  28365. return this._sheen;
  28366. }
  28367. set sheen( value ) {
  28368. if ( this._sheen > 0 !== value > 0 ) {
  28369. this.version ++;
  28370. }
  28371. this._sheen = value;
  28372. }
  28373. /**
  28374. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28375. *
  28376. * Thin, transparent or semitransparent, plastic or glass materials remain
  28377. * largely reflective even if they are fully transmissive. The transmission
  28378. * property can be used to model these materials.
  28379. *
  28380. * When transmission is non-zero, `opacity` should be set to `1`.
  28381. *
  28382. * @type {number}
  28383. * @default 0
  28384. */
  28385. get transmission() {
  28386. return this._transmission;
  28387. }
  28388. set transmission( value ) {
  28389. if ( this._transmission > 0 !== value > 0 ) {
  28390. this.version ++;
  28391. }
  28392. this._transmission = value;
  28393. }
  28394. copy( source ) {
  28395. super.copy( source );
  28396. this.defines = {
  28397. 'STANDARD': '',
  28398. 'PHYSICAL': ''
  28399. };
  28400. this.anisotropy = source.anisotropy;
  28401. this.anisotropyRotation = source.anisotropyRotation;
  28402. this.anisotropyMap = source.anisotropyMap;
  28403. this.clearcoat = source.clearcoat;
  28404. this.clearcoatMap = source.clearcoatMap;
  28405. this.clearcoatRoughness = source.clearcoatRoughness;
  28406. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28407. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28408. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28409. this.dispersion = source.dispersion;
  28410. this.ior = source.ior;
  28411. this.iridescence = source.iridescence;
  28412. this.iridescenceMap = source.iridescenceMap;
  28413. this.iridescenceIOR = source.iridescenceIOR;
  28414. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28415. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28416. this.sheen = source.sheen;
  28417. this.sheenColor.copy( source.sheenColor );
  28418. this.sheenColorMap = source.sheenColorMap;
  28419. this.sheenRoughness = source.sheenRoughness;
  28420. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28421. this.transmission = source.transmission;
  28422. this.transmissionMap = source.transmissionMap;
  28423. this.thickness = source.thickness;
  28424. this.thicknessMap = source.thicknessMap;
  28425. this.attenuationDistance = source.attenuationDistance;
  28426. this.attenuationColor.copy( source.attenuationColor );
  28427. this.specularIntensity = source.specularIntensity;
  28428. this.specularIntensityMap = source.specularIntensityMap;
  28429. this.specularColor.copy( source.specularColor );
  28430. this.specularColorMap = source.specularColorMap;
  28431. return this;
  28432. }
  28433. }
  28434. /**
  28435. * A material for shiny surfaces with specular highlights.
  28436. *
  28437. * The material uses a non-physically based [Blinn-Phong]{@link https://en.wikipedia.org/wiki/Blinn-Phong_shading_model}
  28438. * model for calculating reflectance. Unlike the Lambertian model used in the
  28439. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28440. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28441. *
  28442. * Performance will generally be greater when using this material over the
  28443. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28444. * some graphical accuracy.
  28445. *
  28446. * @augments Material
  28447. */
  28448. class MeshPhongMaterial extends Material {
  28449. /**
  28450. * Constructs a new mesh phong material.
  28451. *
  28452. * @param {Object} [parameters] - An object with one or more properties
  28453. * defining the material's appearance. Any property of the material
  28454. * (including any property from inherited materials) can be passed
  28455. * in here. Color values can be passed any type of value accepted
  28456. * by {@link Color#set}.
  28457. */
  28458. constructor( parameters ) {
  28459. super();
  28460. /**
  28461. * This flag can be used for type testing.
  28462. *
  28463. * @type {boolean}
  28464. * @readonly
  28465. * @default true
  28466. */
  28467. this.isMeshPhongMaterial = true;
  28468. this.type = 'MeshPhongMaterial';
  28469. /**
  28470. * Color of the material.
  28471. *
  28472. * @type {Color}
  28473. * @default (1,1,1)
  28474. */
  28475. this.color = new Color( 0xffffff ); // diffuse
  28476. /**
  28477. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28478. *
  28479. * This defines how shiny the material is and the color of its shine.
  28480. *
  28481. * @type {Color}
  28482. */
  28483. this.specular = new Color( 0x111111 );
  28484. /**
  28485. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28486. *
  28487. * @type {number}
  28488. * @default 30
  28489. */
  28490. this.shininess = 30;
  28491. /**
  28492. * The color map. May optionally include an alpha channel, typically combined
  28493. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28494. * color is modulated by the diffuse `color`.
  28495. *
  28496. * @type {?Texture}
  28497. * @default null
  28498. */
  28499. this.map = null;
  28500. /**
  28501. * The light map. Requires a second set of UVs.
  28502. *
  28503. * @type {?Texture}
  28504. * @default null
  28505. */
  28506. this.lightMap = null;
  28507. /**
  28508. * Intensity of the baked light.
  28509. *
  28510. * @type {number}
  28511. * @default 1
  28512. */
  28513. this.lightMapIntensity = 1.0;
  28514. /**
  28515. * The red channel of this texture is used as the ambient occlusion map.
  28516. * Requires a second set of UVs.
  28517. *
  28518. * @type {?Texture}
  28519. * @default null
  28520. */
  28521. this.aoMap = null;
  28522. /**
  28523. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28524. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28525. * red channel is also `1`, ambient light is fully occluded on a surface.
  28526. *
  28527. * @type {number}
  28528. * @default 1
  28529. */
  28530. this.aoMapIntensity = 1.0;
  28531. /**
  28532. * Emissive (light) color of the material, essentially a solid color
  28533. * unaffected by other lighting.
  28534. *
  28535. * @type {Color}
  28536. * @default (0,0,0)
  28537. */
  28538. this.emissive = new Color( 0x000000 );
  28539. /**
  28540. * Intensity of the emissive light. Modulates the emissive color.
  28541. *
  28542. * @type {number}
  28543. * @default 1
  28544. */
  28545. this.emissiveIntensity = 1.0;
  28546. /**
  28547. * Set emissive (glow) map. The emissive map color is modulated by the
  28548. * emissive color and the emissive intensity. If you have an emissive map,
  28549. * be sure to set the emissive color to something other than black.
  28550. *
  28551. * @type {?Texture}
  28552. * @default null
  28553. */
  28554. this.emissiveMap = null;
  28555. /**
  28556. * The texture to create a bump map. The black and white values map to the
  28557. * perceived depth in relation to the lights. Bump doesn't actually affect
  28558. * the geometry of the object, only the lighting. If a normal map is defined
  28559. * this will be ignored.
  28560. *
  28561. * @type {?Texture}
  28562. * @default null
  28563. */
  28564. this.bumpMap = null;
  28565. /**
  28566. * How much the bump map affects the material. Typical range is `[0,1]`.
  28567. *
  28568. * @type {number}
  28569. * @default 1
  28570. */
  28571. this.bumpScale = 1;
  28572. /**
  28573. * The texture to create a normal map. The RGB values affect the surface
  28574. * normal for each pixel fragment and change the way the color is lit. Normal
  28575. * maps do not change the actual shape of the surface, only the lighting. In
  28576. * case the material has a normal map authored using the left handed
  28577. * convention, the `y` component of `normalScale` should be negated to compensate
  28578. * for the different handedness.
  28579. *
  28580. * @type {?Texture}
  28581. * @default null
  28582. */
  28583. this.normalMap = null;
  28584. /**
  28585. * The type of normal map.
  28586. *
  28587. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28588. * @default TangentSpaceNormalMap
  28589. */
  28590. this.normalMapType = TangentSpaceNormalMap;
  28591. /**
  28592. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28593. *
  28594. * @type {Vector2}
  28595. * @default (1,1)
  28596. */
  28597. this.normalScale = new Vector2( 1, 1 );
  28598. /**
  28599. * The displacement map affects the position of the mesh's vertices. Unlike
  28600. * other maps which only affect the light and shade of the material the
  28601. * displaced vertices can cast shadows, block other objects, and otherwise
  28602. * act as real geometry. The displacement texture is an image where the value
  28603. * of each pixel (white being the highest) is mapped against, and
  28604. * repositions, the vertices of the mesh.
  28605. *
  28606. * @type {?Texture}
  28607. * @default null
  28608. */
  28609. this.displacementMap = null;
  28610. /**
  28611. * How much the displacement map affects the mesh (where black is no
  28612. * displacement, and white is maximum displacement). Without a displacement
  28613. * map set, this value is not applied.
  28614. *
  28615. * @type {number}
  28616. * @default 0
  28617. */
  28618. this.displacementScale = 1;
  28619. /**
  28620. * The offset of the displacement map's values on the mesh's vertices.
  28621. * The bias is added to the scaled sample of the displacement map.
  28622. * Without a displacement map set, this value is not applied.
  28623. *
  28624. * @type {number}
  28625. * @default 0
  28626. */
  28627. this.displacementBias = 0;
  28628. /**
  28629. * The specular map value affects both how much the specular surface
  28630. * highlight contributes and how much of the environment map affects the
  28631. * surface.
  28632. *
  28633. * @type {?Texture}
  28634. * @default null
  28635. */
  28636. this.specularMap = null;
  28637. /**
  28638. * The alpha map is a grayscale texture that controls the opacity across the
  28639. * surface (black: fully transparent; white: fully opaque).
  28640. *
  28641. * Only the color of the texture is used, ignoring the alpha channel if one
  28642. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28643. * when sampling this texture due to the extra bit of precision provided for
  28644. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28645. * luminance/alpha textures will also still work as expected.
  28646. *
  28647. * @type {?Texture}
  28648. * @default null
  28649. */
  28650. this.alphaMap = null;
  28651. /**
  28652. * The environment map.
  28653. *
  28654. * @type {?Texture}
  28655. * @default null
  28656. */
  28657. this.envMap = null;
  28658. /**
  28659. * The rotation of the environment map in radians.
  28660. *
  28661. * @type {Euler}
  28662. * @default (0,0,0)
  28663. */
  28664. this.envMapRotation = new Euler();
  28665. /**
  28666. * How to combine the result of the surface's color with the environment map, if any.
  28667. *
  28668. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28669. * blend between the two colors.
  28670. *
  28671. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28672. * @default MultiplyOperation
  28673. */
  28674. this.combine = MultiplyOperation;
  28675. /**
  28676. * How much the environment map affects the surface.
  28677. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28678. *
  28679. * @type {number}
  28680. * @default 1
  28681. */
  28682. this.reflectivity = 1;
  28683. /**
  28684. * The index of refraction (IOR) of air (approximately 1) divided by the
  28685. * index of refraction of the material. It is used with environment mapping
  28686. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28687. * The refraction ratio should not exceed `1`.
  28688. *
  28689. * @type {number}
  28690. * @default 0.98
  28691. */
  28692. this.refractionRatio = 0.98;
  28693. /**
  28694. * Renders the geometry as a wireframe.
  28695. *
  28696. * @type {boolean}
  28697. * @default false
  28698. */
  28699. this.wireframe = false;
  28700. /**
  28701. * Controls the thickness of the wireframe.
  28702. *
  28703. * Can only be used with {@link SVGRenderer}.
  28704. *
  28705. * @type {number}
  28706. * @default 1
  28707. */
  28708. this.wireframeLinewidth = 1;
  28709. /**
  28710. * Defines appearance of wireframe ends.
  28711. *
  28712. * Can only be used with {@link SVGRenderer}.
  28713. *
  28714. * @type {('round'|'bevel'|'miter')}
  28715. * @default 'round'
  28716. */
  28717. this.wireframeLinecap = 'round';
  28718. /**
  28719. * Defines appearance of wireframe joints.
  28720. *
  28721. * Can only be used with {@link SVGRenderer}.
  28722. *
  28723. * @type {('round'|'bevel'|'miter')}
  28724. * @default 'round'
  28725. */
  28726. this.wireframeLinejoin = 'round';
  28727. /**
  28728. * Whether the material is rendered with flat shading or not.
  28729. *
  28730. * @type {boolean}
  28731. * @default false
  28732. */
  28733. this.flatShading = false;
  28734. /**
  28735. * Whether the material is affected by fog or not.
  28736. *
  28737. * @type {boolean}
  28738. * @default true
  28739. */
  28740. this.fog = true;
  28741. this.setValues( parameters );
  28742. }
  28743. copy( source ) {
  28744. super.copy( source );
  28745. this.color.copy( source.color );
  28746. this.specular.copy( source.specular );
  28747. this.shininess = source.shininess;
  28748. this.map = source.map;
  28749. this.lightMap = source.lightMap;
  28750. this.lightMapIntensity = source.lightMapIntensity;
  28751. this.aoMap = source.aoMap;
  28752. this.aoMapIntensity = source.aoMapIntensity;
  28753. this.emissive.copy( source.emissive );
  28754. this.emissiveMap = source.emissiveMap;
  28755. this.emissiveIntensity = source.emissiveIntensity;
  28756. this.bumpMap = source.bumpMap;
  28757. this.bumpScale = source.bumpScale;
  28758. this.normalMap = source.normalMap;
  28759. this.normalMapType = source.normalMapType;
  28760. this.normalScale.copy( source.normalScale );
  28761. this.displacementMap = source.displacementMap;
  28762. this.displacementScale = source.displacementScale;
  28763. this.displacementBias = source.displacementBias;
  28764. this.specularMap = source.specularMap;
  28765. this.alphaMap = source.alphaMap;
  28766. this.envMap = source.envMap;
  28767. this.envMapRotation.copy( source.envMapRotation );
  28768. this.combine = source.combine;
  28769. this.reflectivity = source.reflectivity;
  28770. this.refractionRatio = source.refractionRatio;
  28771. this.wireframe = source.wireframe;
  28772. this.wireframeLinewidth = source.wireframeLinewidth;
  28773. this.wireframeLinecap = source.wireframeLinecap;
  28774. this.wireframeLinejoin = source.wireframeLinejoin;
  28775. this.flatShading = source.flatShading;
  28776. this.fog = source.fog;
  28777. return this;
  28778. }
  28779. }
  28780. /**
  28781. * A material implementing toon shading.
  28782. *
  28783. * @augments Material
  28784. */
  28785. class MeshToonMaterial extends Material {
  28786. /**
  28787. * Constructs a new mesh toon material.
  28788. *
  28789. * @param {Object} [parameters] - An object with one or more properties
  28790. * defining the material's appearance. Any property of the material
  28791. * (including any property from inherited materials) can be passed
  28792. * in here. Color values can be passed any type of value accepted
  28793. * by {@link Color#set}.
  28794. */
  28795. constructor( parameters ) {
  28796. super();
  28797. /**
  28798. * This flag can be used for type testing.
  28799. *
  28800. * @type {boolean}
  28801. * @readonly
  28802. * @default true
  28803. */
  28804. this.isMeshToonMaterial = true;
  28805. this.defines = { 'TOON': '' };
  28806. this.type = 'MeshToonMaterial';
  28807. /**
  28808. * Color of the material.
  28809. *
  28810. * @type {Color}
  28811. * @default (1,1,1)
  28812. */
  28813. this.color = new Color( 0xffffff );
  28814. /**
  28815. * The color map. May optionally include an alpha channel, typically combined
  28816. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28817. * color is modulated by the diffuse `color`.
  28818. *
  28819. * @type {?Texture}
  28820. * @default null
  28821. */
  28822. this.map = null;
  28823. /**
  28824. * Gradient map for toon shading. It's required to set
  28825. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28826. * when using this type of texture.
  28827. *
  28828. * @type {?Texture}
  28829. * @default null
  28830. */
  28831. this.gradientMap = null;
  28832. /**
  28833. * The light map. Requires a second set of UVs.
  28834. *
  28835. * @type {?Texture}
  28836. * @default null
  28837. */
  28838. this.lightMap = null;
  28839. /**
  28840. * Intensity of the baked light.
  28841. *
  28842. * @type {number}
  28843. * @default 1
  28844. */
  28845. this.lightMapIntensity = 1.0;
  28846. /**
  28847. * The red channel of this texture is used as the ambient occlusion map.
  28848. * Requires a second set of UVs.
  28849. *
  28850. * @type {?Texture}
  28851. * @default null
  28852. */
  28853. this.aoMap = null;
  28854. /**
  28855. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28856. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28857. * red channel is also `1`, ambient light is fully occluded on a surface.
  28858. *
  28859. * @type {number}
  28860. * @default 1
  28861. */
  28862. this.aoMapIntensity = 1.0;
  28863. /**
  28864. * Emissive (light) color of the material, essentially a solid color
  28865. * unaffected by other lighting.
  28866. *
  28867. * @type {Color}
  28868. * @default (0,0,0)
  28869. */
  28870. this.emissive = new Color( 0x000000 );
  28871. /**
  28872. * Intensity of the emissive light. Modulates the emissive color.
  28873. *
  28874. * @type {number}
  28875. * @default 1
  28876. */
  28877. this.emissiveIntensity = 1.0;
  28878. /**
  28879. * Set emissive (glow) map. The emissive map color is modulated by the
  28880. * emissive color and the emissive intensity. If you have an emissive map,
  28881. * be sure to set the emissive color to something other than black.
  28882. *
  28883. * @type {?Texture}
  28884. * @default null
  28885. */
  28886. this.emissiveMap = null;
  28887. /**
  28888. * The texture to create a bump map. The black and white values map to the
  28889. * perceived depth in relation to the lights. Bump doesn't actually affect
  28890. * the geometry of the object, only the lighting. If a normal map is defined
  28891. * this will be ignored.
  28892. *
  28893. * @type {?Texture}
  28894. * @default null
  28895. */
  28896. this.bumpMap = null;
  28897. /**
  28898. * How much the bump map affects the material. Typical range is `[0,1]`.
  28899. *
  28900. * @type {number}
  28901. * @default 1
  28902. */
  28903. this.bumpScale = 1;
  28904. /**
  28905. * The texture to create a normal map. The RGB values affect the surface
  28906. * normal for each pixel fragment and change the way the color is lit. Normal
  28907. * maps do not change the actual shape of the surface, only the lighting. In
  28908. * case the material has a normal map authored using the left handed
  28909. * convention, the `y` component of `normalScale` should be negated to compensate
  28910. * for the different handedness.
  28911. *
  28912. * @type {?Texture}
  28913. * @default null
  28914. */
  28915. this.normalMap = null;
  28916. /**
  28917. * The type of normal map.
  28918. *
  28919. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28920. * @default TangentSpaceNormalMap
  28921. */
  28922. this.normalMapType = TangentSpaceNormalMap;
  28923. /**
  28924. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28925. *
  28926. * @type {Vector2}
  28927. * @default (1,1)
  28928. */
  28929. this.normalScale = new Vector2( 1, 1 );
  28930. /**
  28931. * The displacement map affects the position of the mesh's vertices. Unlike
  28932. * other maps which only affect the light and shade of the material the
  28933. * displaced vertices can cast shadows, block other objects, and otherwise
  28934. * act as real geometry. The displacement texture is an image where the value
  28935. * of each pixel (white being the highest) is mapped against, and
  28936. * repositions, the vertices of the mesh.
  28937. *
  28938. * @type {?Texture}
  28939. * @default null
  28940. */
  28941. this.displacementMap = null;
  28942. /**
  28943. * How much the displacement map affects the mesh (where black is no
  28944. * displacement, and white is maximum displacement). Without a displacement
  28945. * map set, this value is not applied.
  28946. *
  28947. * @type {number}
  28948. * @default 0
  28949. */
  28950. this.displacementScale = 1;
  28951. /**
  28952. * The offset of the displacement map's values on the mesh's vertices.
  28953. * The bias is added to the scaled sample of the displacement map.
  28954. * Without a displacement map set, this value is not applied.
  28955. *
  28956. * @type {number}
  28957. * @default 0
  28958. */
  28959. this.displacementBias = 0;
  28960. /**
  28961. * The alpha map is a grayscale texture that controls the opacity across the
  28962. * surface (black: fully transparent; white: fully opaque).
  28963. *
  28964. * Only the color of the texture is used, ignoring the alpha channel if one
  28965. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28966. * when sampling this texture due to the extra bit of precision provided for
  28967. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28968. * luminance/alpha textures will also still work as expected.
  28969. *
  28970. * @type {?Texture}
  28971. * @default null
  28972. */
  28973. this.alphaMap = null;
  28974. /**
  28975. * Renders the geometry as a wireframe.
  28976. *
  28977. * @type {boolean}
  28978. * @default false
  28979. */
  28980. this.wireframe = false;
  28981. /**
  28982. * Controls the thickness of the wireframe.
  28983. *
  28984. * Can only be used with {@link SVGRenderer}.
  28985. *
  28986. * @type {number}
  28987. * @default 1
  28988. */
  28989. this.wireframeLinewidth = 1;
  28990. /**
  28991. * Defines appearance of wireframe ends.
  28992. *
  28993. * Can only be used with {@link SVGRenderer}.
  28994. *
  28995. * @type {('round'|'bevel'|'miter')}
  28996. * @default 'round'
  28997. */
  28998. this.wireframeLinecap = 'round';
  28999. /**
  29000. * Defines appearance of wireframe joints.
  29001. *
  29002. * Can only be used with {@link SVGRenderer}.
  29003. *
  29004. * @type {('round'|'bevel'|'miter')}
  29005. * @default 'round'
  29006. */
  29007. this.wireframeLinejoin = 'round';
  29008. /**
  29009. * Whether the material is affected by fog or not.
  29010. *
  29011. * @type {boolean}
  29012. * @default true
  29013. */
  29014. this.fog = true;
  29015. this.setValues( parameters );
  29016. }
  29017. copy( source ) {
  29018. super.copy( source );
  29019. this.color.copy( source.color );
  29020. this.map = source.map;
  29021. this.gradientMap = source.gradientMap;
  29022. this.lightMap = source.lightMap;
  29023. this.lightMapIntensity = source.lightMapIntensity;
  29024. this.aoMap = source.aoMap;
  29025. this.aoMapIntensity = source.aoMapIntensity;
  29026. this.emissive.copy( source.emissive );
  29027. this.emissiveMap = source.emissiveMap;
  29028. this.emissiveIntensity = source.emissiveIntensity;
  29029. this.bumpMap = source.bumpMap;
  29030. this.bumpScale = source.bumpScale;
  29031. this.normalMap = source.normalMap;
  29032. this.normalMapType = source.normalMapType;
  29033. this.normalScale.copy( source.normalScale );
  29034. this.displacementMap = source.displacementMap;
  29035. this.displacementScale = source.displacementScale;
  29036. this.displacementBias = source.displacementBias;
  29037. this.alphaMap = source.alphaMap;
  29038. this.wireframe = source.wireframe;
  29039. this.wireframeLinewidth = source.wireframeLinewidth;
  29040. this.wireframeLinecap = source.wireframeLinecap;
  29041. this.wireframeLinejoin = source.wireframeLinejoin;
  29042. this.fog = source.fog;
  29043. return this;
  29044. }
  29045. }
  29046. /**
  29047. * A material that maps the normal vectors to RGB colors.
  29048. *
  29049. * @augments Material
  29050. */
  29051. class MeshNormalMaterial extends Material {
  29052. /**
  29053. * Constructs a new mesh normal material.
  29054. *
  29055. * @param {Object} [parameters] - An object with one or more properties
  29056. * defining the material's appearance. Any property of the material
  29057. * (including any property from inherited materials) can be passed
  29058. * in here. Color values can be passed any type of value accepted
  29059. * by {@link Color#set}.
  29060. */
  29061. constructor( parameters ) {
  29062. super();
  29063. /**
  29064. * This flag can be used for type testing.
  29065. *
  29066. * @type {boolean}
  29067. * @readonly
  29068. * @default true
  29069. */
  29070. this.isMeshNormalMaterial = true;
  29071. this.type = 'MeshNormalMaterial';
  29072. /**
  29073. * The texture to create a bump map. The black and white values map to the
  29074. * perceived depth in relation to the lights. Bump doesn't actually affect
  29075. * the geometry of the object, only the lighting. If a normal map is defined
  29076. * this will be ignored.
  29077. *
  29078. * @type {?Texture}
  29079. * @default null
  29080. */
  29081. this.bumpMap = null;
  29082. /**
  29083. * How much the bump map affects the material. Typical range is `[0,1]`.
  29084. *
  29085. * @type {number}
  29086. * @default 1
  29087. */
  29088. this.bumpScale = 1;
  29089. /**
  29090. * The texture to create a normal map. The RGB values affect the surface
  29091. * normal for each pixel fragment and change the way the color is lit. Normal
  29092. * maps do not change the actual shape of the surface, only the lighting. In
  29093. * case the material has a normal map authored using the left handed
  29094. * convention, the `y` component of `normalScale` should be negated to compensate
  29095. * for the different handedness.
  29096. *
  29097. * @type {?Texture}
  29098. * @default null
  29099. */
  29100. this.normalMap = null;
  29101. /**
  29102. * The type of normal map.
  29103. *
  29104. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29105. * @default TangentSpaceNormalMap
  29106. */
  29107. this.normalMapType = TangentSpaceNormalMap;
  29108. /**
  29109. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29110. *
  29111. * @type {Vector2}
  29112. * @default (1,1)
  29113. */
  29114. this.normalScale = new Vector2( 1, 1 );
  29115. /**
  29116. * The displacement map affects the position of the mesh's vertices. Unlike
  29117. * other maps which only affect the light and shade of the material the
  29118. * displaced vertices can cast shadows, block other objects, and otherwise
  29119. * act as real geometry. The displacement texture is an image where the value
  29120. * of each pixel (white being the highest) is mapped against, and
  29121. * repositions, the vertices of the mesh.
  29122. *
  29123. * @type {?Texture}
  29124. * @default null
  29125. */
  29126. this.displacementMap = null;
  29127. /**
  29128. * How much the displacement map affects the mesh (where black is no
  29129. * displacement, and white is maximum displacement). Without a displacement
  29130. * map set, this value is not applied.
  29131. *
  29132. * @type {number}
  29133. * @default 0
  29134. */
  29135. this.displacementScale = 1;
  29136. /**
  29137. * The offset of the displacement map's values on the mesh's vertices.
  29138. * The bias is added to the scaled sample of the displacement map.
  29139. * Without a displacement map set, this value is not applied.
  29140. *
  29141. * @type {number}
  29142. * @default 0
  29143. */
  29144. this.displacementBias = 0;
  29145. /**
  29146. * Renders the geometry as a wireframe.
  29147. *
  29148. * @type {boolean}
  29149. * @default false
  29150. */
  29151. this.wireframe = false;
  29152. /**
  29153. * Controls the thickness of the wireframe.
  29154. *
  29155. * WebGL and WebGPU ignore this property and always render
  29156. * 1 pixel wide lines.
  29157. *
  29158. * @type {number}
  29159. * @default 1
  29160. */
  29161. this.wireframeLinewidth = 1;
  29162. /**
  29163. * Whether the material is rendered with flat shading or not.
  29164. *
  29165. * @type {boolean}
  29166. * @default false
  29167. */
  29168. this.flatShading = false;
  29169. this.setValues( parameters );
  29170. }
  29171. copy( source ) {
  29172. super.copy( source );
  29173. this.bumpMap = source.bumpMap;
  29174. this.bumpScale = source.bumpScale;
  29175. this.normalMap = source.normalMap;
  29176. this.normalMapType = source.normalMapType;
  29177. this.normalScale.copy( source.normalScale );
  29178. this.displacementMap = source.displacementMap;
  29179. this.displacementScale = source.displacementScale;
  29180. this.displacementBias = source.displacementBias;
  29181. this.wireframe = source.wireframe;
  29182. this.wireframeLinewidth = source.wireframeLinewidth;
  29183. this.flatShading = source.flatShading;
  29184. return this;
  29185. }
  29186. }
  29187. /**
  29188. * A material for non-shiny surfaces, without specular highlights.
  29189. *
  29190. * The material uses a non-physically based [Lambertian]{@link https://en.wikipedia.org/wiki/Lambertian_reflectance}
  29191. * model for calculating reflectance. This can simulate some surfaces (such
  29192. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29193. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29194. * shading.
  29195. *
  29196. * Due to the simplicity of the reflectance and illumination models,
  29197. * performance will be greater when using this material over the
  29198. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29199. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29200. *
  29201. * @augments Material
  29202. */
  29203. class MeshLambertMaterial extends Material {
  29204. /**
  29205. * Constructs a new mesh lambert material.
  29206. *
  29207. * @param {Object} [parameters] - An object with one or more properties
  29208. * defining the material's appearance. Any property of the material
  29209. * (including any property from inherited materials) can be passed
  29210. * in here. Color values can be passed any type of value accepted
  29211. * by {@link Color#set}.
  29212. */
  29213. constructor( parameters ) {
  29214. super();
  29215. /**
  29216. * This flag can be used for type testing.
  29217. *
  29218. * @type {boolean}
  29219. * @readonly
  29220. * @default true
  29221. */
  29222. this.isMeshLambertMaterial = true;
  29223. this.type = 'MeshLambertMaterial';
  29224. /**
  29225. * Color of the material.
  29226. *
  29227. * @type {Color}
  29228. * @default (1,1,1)
  29229. */
  29230. this.color = new Color( 0xffffff ); // diffuse
  29231. /**
  29232. * The color map. May optionally include an alpha channel, typically combined
  29233. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29234. * color is modulated by the diffuse `color`.
  29235. *
  29236. * @type {?Texture}
  29237. * @default null
  29238. */
  29239. this.map = null;
  29240. /**
  29241. * The light map. Requires a second set of UVs.
  29242. *
  29243. * @type {?Texture}
  29244. * @default null
  29245. */
  29246. this.lightMap = null;
  29247. /**
  29248. * Intensity of the baked light.
  29249. *
  29250. * @type {number}
  29251. * @default 1
  29252. */
  29253. this.lightMapIntensity = 1.0;
  29254. /**
  29255. * The red channel of this texture is used as the ambient occlusion map.
  29256. * Requires a second set of UVs.
  29257. *
  29258. * @type {?Texture}
  29259. * @default null
  29260. */
  29261. this.aoMap = null;
  29262. /**
  29263. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29264. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29265. * red channel is also `1`, ambient light is fully occluded on a surface.
  29266. *
  29267. * @type {number}
  29268. * @default 1
  29269. */
  29270. this.aoMapIntensity = 1.0;
  29271. /**
  29272. * Emissive (light) color of the material, essentially a solid color
  29273. * unaffected by other lighting.
  29274. *
  29275. * @type {Color}
  29276. * @default (0,0,0)
  29277. */
  29278. this.emissive = new Color( 0x000000 );
  29279. /**
  29280. * Intensity of the emissive light. Modulates the emissive color.
  29281. *
  29282. * @type {number}
  29283. * @default 1
  29284. */
  29285. this.emissiveIntensity = 1.0;
  29286. /**
  29287. * Set emissive (glow) map. The emissive map color is modulated by the
  29288. * emissive color and the emissive intensity. If you have an emissive map,
  29289. * be sure to set the emissive color to something other than black.
  29290. *
  29291. * @type {?Texture}
  29292. * @default null
  29293. */
  29294. this.emissiveMap = null;
  29295. /**
  29296. * The texture to create a bump map. The black and white values map to the
  29297. * perceived depth in relation to the lights. Bump doesn't actually affect
  29298. * the geometry of the object, only the lighting. If a normal map is defined
  29299. * this will be ignored.
  29300. *
  29301. * @type {?Texture}
  29302. * @default null
  29303. */
  29304. this.bumpMap = null;
  29305. /**
  29306. * How much the bump map affects the material. Typical range is `[0,1]`.
  29307. *
  29308. * @type {number}
  29309. * @default 1
  29310. */
  29311. this.bumpScale = 1;
  29312. /**
  29313. * The texture to create a normal map. The RGB values affect the surface
  29314. * normal for each pixel fragment and change the way the color is lit. Normal
  29315. * maps do not change the actual shape of the surface, only the lighting. In
  29316. * case the material has a normal map authored using the left handed
  29317. * convention, the `y` component of `normalScale` should be negated to compensate
  29318. * for the different handedness.
  29319. *
  29320. * @type {?Texture}
  29321. * @default null
  29322. */
  29323. this.normalMap = null;
  29324. /**
  29325. * The type of normal map.
  29326. *
  29327. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29328. * @default TangentSpaceNormalMap
  29329. */
  29330. this.normalMapType = TangentSpaceNormalMap;
  29331. /**
  29332. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29333. *
  29334. * @type {Vector2}
  29335. * @default (1,1)
  29336. */
  29337. this.normalScale = new Vector2( 1, 1 );
  29338. /**
  29339. * The displacement map affects the position of the mesh's vertices. Unlike
  29340. * other maps which only affect the light and shade of the material the
  29341. * displaced vertices can cast shadows, block other objects, and otherwise
  29342. * act as real geometry. The displacement texture is an image where the value
  29343. * of each pixel (white being the highest) is mapped against, and
  29344. * repositions, the vertices of the mesh.
  29345. *
  29346. * @type {?Texture}
  29347. * @default null
  29348. */
  29349. this.displacementMap = null;
  29350. /**
  29351. * How much the displacement map affects the mesh (where black is no
  29352. * displacement, and white is maximum displacement). Without a displacement
  29353. * map set, this value is not applied.
  29354. *
  29355. * @type {number}
  29356. * @default 0
  29357. */
  29358. this.displacementScale = 1;
  29359. /**
  29360. * The offset of the displacement map's values on the mesh's vertices.
  29361. * The bias is added to the scaled sample of the displacement map.
  29362. * Without a displacement map set, this value is not applied.
  29363. *
  29364. * @type {number}
  29365. * @default 0
  29366. */
  29367. this.displacementBias = 0;
  29368. /**
  29369. * Specular map used by the material.
  29370. *
  29371. * @type {?Texture}
  29372. * @default null
  29373. */
  29374. this.specularMap = null;
  29375. /**
  29376. * The alpha map is a grayscale texture that controls the opacity across the
  29377. * surface (black: fully transparent; white: fully opaque).
  29378. *
  29379. * Only the color of the texture is used, ignoring the alpha channel if one
  29380. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29381. * when sampling this texture due to the extra bit of precision provided for
  29382. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29383. * luminance/alpha textures will also still work as expected.
  29384. *
  29385. * @type {?Texture}
  29386. * @default null
  29387. */
  29388. this.alphaMap = null;
  29389. /**
  29390. * The environment map.
  29391. *
  29392. * @type {?Texture}
  29393. * @default null
  29394. */
  29395. this.envMap = null;
  29396. /**
  29397. * The rotation of the environment map in radians.
  29398. *
  29399. * @type {Euler}
  29400. * @default (0,0,0)
  29401. */
  29402. this.envMapRotation = new Euler();
  29403. /**
  29404. * How to combine the result of the surface's color with the environment map, if any.
  29405. *
  29406. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29407. * blend between the two colors.
  29408. *
  29409. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29410. * @default MultiplyOperation
  29411. */
  29412. this.combine = MultiplyOperation;
  29413. /**
  29414. * How much the environment map affects the surface.
  29415. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29416. *
  29417. * @type {number}
  29418. * @default 1
  29419. */
  29420. this.reflectivity = 1;
  29421. /**
  29422. * The index of refraction (IOR) of air (approximately 1) divided by the
  29423. * index of refraction of the material. It is used with environment mapping
  29424. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29425. * The refraction ratio should not exceed `1`.
  29426. *
  29427. * @type {number}
  29428. * @default 0.98
  29429. */
  29430. this.refractionRatio = 0.98;
  29431. /**
  29432. * Renders the geometry as a wireframe.
  29433. *
  29434. * @type {boolean}
  29435. * @default false
  29436. */
  29437. this.wireframe = false;
  29438. /**
  29439. * Controls the thickness of the wireframe.
  29440. *
  29441. * Can only be used with {@link SVGRenderer}.
  29442. *
  29443. * @type {number}
  29444. * @default 1
  29445. */
  29446. this.wireframeLinewidth = 1;
  29447. /**
  29448. * Defines appearance of wireframe ends.
  29449. *
  29450. * Can only be used with {@link SVGRenderer}.
  29451. *
  29452. * @type {('round'|'bevel'|'miter')}
  29453. * @default 'round'
  29454. */
  29455. this.wireframeLinecap = 'round';
  29456. /**
  29457. * Defines appearance of wireframe joints.
  29458. *
  29459. * Can only be used with {@link SVGRenderer}.
  29460. *
  29461. * @type {('round'|'bevel'|'miter')}
  29462. * @default 'round'
  29463. */
  29464. this.wireframeLinejoin = 'round';
  29465. /**
  29466. * Whether the material is rendered with flat shading or not.
  29467. *
  29468. * @type {boolean}
  29469. * @default false
  29470. */
  29471. this.flatShading = false;
  29472. /**
  29473. * Whether the material is affected by fog or not.
  29474. *
  29475. * @type {boolean}
  29476. * @default true
  29477. */
  29478. this.fog = true;
  29479. this.setValues( parameters );
  29480. }
  29481. copy( source ) {
  29482. super.copy( source );
  29483. this.color.copy( source.color );
  29484. this.map = source.map;
  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.specularMap = source.specularMap;
  29501. this.alphaMap = source.alphaMap;
  29502. this.envMap = source.envMap;
  29503. this.envMapRotation.copy( source.envMapRotation );
  29504. this.combine = source.combine;
  29505. this.reflectivity = source.reflectivity;
  29506. this.refractionRatio = source.refractionRatio;
  29507. this.wireframe = source.wireframe;
  29508. this.wireframeLinewidth = source.wireframeLinewidth;
  29509. this.wireframeLinecap = source.wireframeLinecap;
  29510. this.wireframeLinejoin = source.wireframeLinejoin;
  29511. this.flatShading = source.flatShading;
  29512. this.fog = source.fog;
  29513. return this;
  29514. }
  29515. }
  29516. /**
  29517. * A material for drawing geometry by depth. Depth is based off of the camera
  29518. * near and far plane. White is nearest, black is farthest.
  29519. *
  29520. * @augments Material
  29521. */
  29522. class MeshDepthMaterial extends Material {
  29523. /**
  29524. * Constructs a new mesh depth material.
  29525. *
  29526. * @param {Object} [parameters] - An object with one or more properties
  29527. * defining the material's appearance. Any property of the material
  29528. * (including any property from inherited materials) can be passed
  29529. * in here. Color values can be passed any type of value accepted
  29530. * by {@link Color#set}.
  29531. */
  29532. constructor( parameters ) {
  29533. super();
  29534. /**
  29535. * This flag can be used for type testing.
  29536. *
  29537. * @type {boolean}
  29538. * @readonly
  29539. * @default true
  29540. */
  29541. this.isMeshDepthMaterial = true;
  29542. this.type = 'MeshDepthMaterial';
  29543. /**
  29544. * Type for depth packing.
  29545. *
  29546. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29547. * @default BasicDepthPacking
  29548. */
  29549. this.depthPacking = BasicDepthPacking;
  29550. /**
  29551. * The color map. May optionally include an alpha channel, typically combined
  29552. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29553. *
  29554. * @type {?Texture}
  29555. * @default null
  29556. */
  29557. this.map = null;
  29558. /**
  29559. * The alpha map is a grayscale texture that controls the opacity across the
  29560. * surface (black: fully transparent; white: fully opaque).
  29561. *
  29562. * Only the color of the texture is used, ignoring the alpha channel if one
  29563. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29564. * when sampling this texture due to the extra bit of precision provided for
  29565. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29566. * luminance/alpha textures will also still work as expected.
  29567. *
  29568. * @type {?Texture}
  29569. * @default null
  29570. */
  29571. this.alphaMap = null;
  29572. /**
  29573. * The displacement map affects the position of the mesh's vertices. Unlike
  29574. * other maps which only affect the light and shade of the material the
  29575. * displaced vertices can cast shadows, block other objects, and otherwise
  29576. * act as real geometry. The displacement texture is an image where the value
  29577. * of each pixel (white being the highest) is mapped against, and
  29578. * repositions, the vertices of the mesh.
  29579. *
  29580. * @type {?Texture}
  29581. * @default null
  29582. */
  29583. this.displacementMap = null;
  29584. /**
  29585. * How much the displacement map affects the mesh (where black is no
  29586. * displacement, and white is maximum displacement). Without a displacement
  29587. * map set, this value is not applied.
  29588. *
  29589. * @type {number}
  29590. * @default 0
  29591. */
  29592. this.displacementScale = 1;
  29593. /**
  29594. * The offset of the displacement map's values on the mesh's vertices.
  29595. * The bias is added to the scaled sample of the displacement map.
  29596. * Without a displacement map set, this value is not applied.
  29597. *
  29598. * @type {number}
  29599. * @default 0
  29600. */
  29601. this.displacementBias = 0;
  29602. /**
  29603. * Renders the geometry as a wireframe.
  29604. *
  29605. * @type {boolean}
  29606. * @default false
  29607. */
  29608. this.wireframe = false;
  29609. /**
  29610. * Controls the thickness of the wireframe.
  29611. *
  29612. * WebGL and WebGPU ignore this property and always render
  29613. * 1 pixel wide lines.
  29614. *
  29615. * @type {number}
  29616. * @default 1
  29617. */
  29618. this.wireframeLinewidth = 1;
  29619. this.setValues( parameters );
  29620. }
  29621. copy( source ) {
  29622. super.copy( source );
  29623. this.depthPacking = source.depthPacking;
  29624. this.map = source.map;
  29625. this.alphaMap = source.alphaMap;
  29626. this.displacementMap = source.displacementMap;
  29627. this.displacementScale = source.displacementScale;
  29628. this.displacementBias = source.displacementBias;
  29629. this.wireframe = source.wireframe;
  29630. this.wireframeLinewidth = source.wireframeLinewidth;
  29631. return this;
  29632. }
  29633. }
  29634. /**
  29635. * A material used internally for implementing shadow mapping with
  29636. * point lights.
  29637. *
  29638. * Can also be used to customize the shadow casting of an object by assigning
  29639. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29640. * The following examples demonstrates this approach in order to ensure
  29641. * transparent parts of objects do no cast shadows.
  29642. *
  29643. * @augments Material
  29644. */
  29645. class MeshDistanceMaterial extends Material {
  29646. /**
  29647. * Constructs a new mesh distance material.
  29648. *
  29649. * @param {Object} [parameters] - An object with one or more properties
  29650. * defining the material's appearance. Any property of the material
  29651. * (including any property from inherited materials) can be passed
  29652. * in here. Color values can be passed any type of value accepted
  29653. * by {@link Color#set}.
  29654. */
  29655. constructor( parameters ) {
  29656. super();
  29657. /**
  29658. * This flag can be used for type testing.
  29659. *
  29660. * @type {boolean}
  29661. * @readonly
  29662. * @default true
  29663. */
  29664. this.isMeshDistanceMaterial = true;
  29665. this.type = 'MeshDistanceMaterial';
  29666. /**
  29667. * The color map. May optionally include an alpha channel, typically combined
  29668. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29669. *
  29670. * @type {?Texture}
  29671. * @default null
  29672. */
  29673. this.map = null;
  29674. /**
  29675. * The alpha map is a grayscale texture that controls the opacity across the
  29676. * surface (black: fully transparent; white: fully opaque).
  29677. *
  29678. * Only the color of the texture is used, ignoring the alpha channel if one
  29679. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29680. * when sampling this texture due to the extra bit of precision provided for
  29681. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29682. * luminance/alpha textures will also still work as expected.
  29683. *
  29684. * @type {?Texture}
  29685. * @default null
  29686. */
  29687. this.alphaMap = null;
  29688. /**
  29689. * The displacement map affects the position of the mesh's vertices. Unlike
  29690. * other maps which only affect the light and shade of the material the
  29691. * displaced vertices can cast shadows, block other objects, and otherwise
  29692. * act as real geometry. The displacement texture is an image where the value
  29693. * of each pixel (white being the highest) is mapped against, and
  29694. * repositions, the vertices of the mesh.
  29695. *
  29696. * @type {?Texture}
  29697. * @default null
  29698. */
  29699. this.displacementMap = null;
  29700. /**
  29701. * How much the displacement map affects the mesh (where black is no
  29702. * displacement, and white is maximum displacement). Without a displacement
  29703. * map set, this value is not applied.
  29704. *
  29705. * @type {number}
  29706. * @default 0
  29707. */
  29708. this.displacementScale = 1;
  29709. /**
  29710. * The offset of the displacement map's values on the mesh's vertices.
  29711. * The bias is added to the scaled sample of the displacement map.
  29712. * Without a displacement map set, this value is not applied.
  29713. *
  29714. * @type {number}
  29715. * @default 0
  29716. */
  29717. this.displacementBias = 0;
  29718. this.setValues( parameters );
  29719. }
  29720. copy( source ) {
  29721. super.copy( source );
  29722. this.map = source.map;
  29723. this.alphaMap = source.alphaMap;
  29724. this.displacementMap = source.displacementMap;
  29725. this.displacementScale = source.displacementScale;
  29726. this.displacementBias = source.displacementBias;
  29727. return this;
  29728. }
  29729. }
  29730. /**
  29731. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29732. * material color and shading.
  29733. *
  29734. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29735. * baked lighting. It will cast a shadow onto an object that receives shadows
  29736. * (and shadow clipping works), but it will not self-shadow or receive
  29737. * shadows.
  29738. *
  29739. * @augments Material
  29740. */
  29741. class MeshMatcapMaterial extends Material {
  29742. /**
  29743. * Constructs a new mesh matcap material.
  29744. *
  29745. * @param {Object} [parameters] - An object with one or more properties
  29746. * defining the material's appearance. Any property of the material
  29747. * (including any property from inherited materials) can be passed
  29748. * in here. Color values can be passed any type of value accepted
  29749. * by {@link Color#set}.
  29750. */
  29751. constructor( parameters ) {
  29752. super();
  29753. /**
  29754. * This flag can be used for type testing.
  29755. *
  29756. * @type {boolean}
  29757. * @readonly
  29758. * @default true
  29759. */
  29760. this.isMeshMatcapMaterial = true;
  29761. this.defines = { 'MATCAP': '' };
  29762. this.type = 'MeshMatcapMaterial';
  29763. /**
  29764. * Color of the material.
  29765. *
  29766. * @type {Color}
  29767. * @default (1,1,1)
  29768. */
  29769. this.color = new Color( 0xffffff ); // diffuse
  29770. /**
  29771. * The matcap map.
  29772. *
  29773. * @type {?Texture}
  29774. * @default null
  29775. */
  29776. this.matcap = null;
  29777. /**
  29778. * The color map. May optionally include an alpha channel, typically combined
  29779. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29780. * color is modulated by the diffuse `color`.
  29781. *
  29782. * @type {?Texture}
  29783. * @default null
  29784. */
  29785. this.map = null;
  29786. /**
  29787. * The texture to create a bump map. The black and white values map to the
  29788. * perceived depth in relation to the lights. Bump doesn't actually affect
  29789. * the geometry of the object, only the lighting. If a normal map is defined
  29790. * this will be ignored.
  29791. *
  29792. * @type {?Texture}
  29793. * @default null
  29794. */
  29795. this.bumpMap = null;
  29796. /**
  29797. * How much the bump map affects the material. Typical range is `[0,1]`.
  29798. *
  29799. * @type {number}
  29800. * @default 1
  29801. */
  29802. this.bumpScale = 1;
  29803. /**
  29804. * The texture to create a normal map. The RGB values affect the surface
  29805. * normal for each pixel fragment and change the way the color is lit. Normal
  29806. * maps do not change the actual shape of the surface, only the lighting. In
  29807. * case the material has a normal map authored using the left handed
  29808. * convention, the `y` component of `normalScale` should be negated to compensate
  29809. * for the different handedness.
  29810. *
  29811. * @type {?Texture}
  29812. * @default null
  29813. */
  29814. this.normalMap = null;
  29815. /**
  29816. * The type of normal map.
  29817. *
  29818. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29819. * @default TangentSpaceNormalMap
  29820. */
  29821. this.normalMapType = TangentSpaceNormalMap;
  29822. /**
  29823. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29824. *
  29825. * @type {Vector2}
  29826. * @default (1,1)
  29827. */
  29828. this.normalScale = new Vector2( 1, 1 );
  29829. /**
  29830. * The displacement map affects the position of the mesh's vertices. Unlike
  29831. * other maps which only affect the light and shade of the material the
  29832. * displaced vertices can cast shadows, block other objects, and otherwise
  29833. * act as real geometry. The displacement texture is an image where the value
  29834. * of each pixel (white being the highest) is mapped against, and
  29835. * repositions, the vertices of the mesh.
  29836. *
  29837. * @type {?Texture}
  29838. * @default null
  29839. */
  29840. this.displacementMap = null;
  29841. /**
  29842. * How much the displacement map affects the mesh (where black is no
  29843. * displacement, and white is maximum displacement). Without a displacement
  29844. * map set, this value is not applied.
  29845. *
  29846. * @type {number}
  29847. * @default 0
  29848. */
  29849. this.displacementScale = 1;
  29850. /**
  29851. * The offset of the displacement map's values on the mesh's vertices.
  29852. * The bias is added to the scaled sample of the displacement map.
  29853. * Without a displacement map set, this value is not applied.
  29854. *
  29855. * @type {number}
  29856. * @default 0
  29857. */
  29858. this.displacementBias = 0;
  29859. /**
  29860. * The alpha map is a grayscale texture that controls the opacity across the
  29861. * surface (black: fully transparent; white: fully opaque).
  29862. *
  29863. * Only the color of the texture is used, ignoring the alpha channel if one
  29864. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29865. * when sampling this texture due to the extra bit of precision provided for
  29866. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29867. * luminance/alpha textures will also still work as expected.
  29868. *
  29869. * @type {?Texture}
  29870. * @default null
  29871. */
  29872. this.alphaMap = null;
  29873. /**
  29874. * Whether the material is rendered with flat shading or not.
  29875. *
  29876. * @type {boolean}
  29877. * @default false
  29878. */
  29879. this.flatShading = false;
  29880. /**
  29881. * Whether the material is affected by fog or not.
  29882. *
  29883. * @type {boolean}
  29884. * @default true
  29885. */
  29886. this.fog = true;
  29887. this.setValues( parameters );
  29888. }
  29889. copy( source ) {
  29890. super.copy( source );
  29891. this.defines = { 'MATCAP': '' };
  29892. this.color.copy( source.color );
  29893. this.matcap = source.matcap;
  29894. this.map = source.map;
  29895. this.bumpMap = source.bumpMap;
  29896. this.bumpScale = source.bumpScale;
  29897. this.normalMap = source.normalMap;
  29898. this.normalMapType = source.normalMapType;
  29899. this.normalScale.copy( source.normalScale );
  29900. this.displacementMap = source.displacementMap;
  29901. this.displacementScale = source.displacementScale;
  29902. this.displacementBias = source.displacementBias;
  29903. this.alphaMap = source.alphaMap;
  29904. this.flatShading = source.flatShading;
  29905. this.fog = source.fog;
  29906. return this;
  29907. }
  29908. }
  29909. /**
  29910. * A material for rendering line primitives.
  29911. *
  29912. * Materials define the appearance of renderable 3D objects.
  29913. *
  29914. * ```js
  29915. * const material = new THREE.LineDashedMaterial( {
  29916. * color: 0xffffff,
  29917. * scale: 1,
  29918. * dashSize: 3,
  29919. * gapSize: 1,
  29920. * } );
  29921. * ```
  29922. *
  29923. * @augments LineBasicMaterial
  29924. */
  29925. class LineDashedMaterial extends LineBasicMaterial {
  29926. /**
  29927. * Constructs a new line dashed material.
  29928. *
  29929. * @param {Object} [parameters] - An object with one or more properties
  29930. * defining the material's appearance. Any property of the material
  29931. * (including any property from inherited materials) can be passed
  29932. * in here. Color values can be passed any type of value accepted
  29933. * by {@link Color#set}.
  29934. */
  29935. constructor( parameters ) {
  29936. super();
  29937. /**
  29938. * This flag can be used for type testing.
  29939. *
  29940. * @type {boolean}
  29941. * @readonly
  29942. * @default true
  29943. */
  29944. this.isLineDashedMaterial = true;
  29945. this.type = 'LineDashedMaterial';
  29946. /**
  29947. * The scale of the dashed part of a line.
  29948. *
  29949. * @type {number}
  29950. * @default 1
  29951. */
  29952. this.scale = 1;
  29953. /**
  29954. * The size of the dash. This is both the gap with the stroke.
  29955. *
  29956. * @type {number}
  29957. * @default 3
  29958. */
  29959. this.dashSize = 3;
  29960. /**
  29961. * The size of the gap.
  29962. *
  29963. * @type {number}
  29964. * @default 1
  29965. */
  29966. this.gapSize = 1;
  29967. this.setValues( parameters );
  29968. }
  29969. copy( source ) {
  29970. super.copy( source );
  29971. this.scale = source.scale;
  29972. this.dashSize = source.dashSize;
  29973. this.gapSize = source.gapSize;
  29974. return this;
  29975. }
  29976. }
  29977. /**
  29978. * Converts an array to a specific type.
  29979. *
  29980. * @param {TypedArray|Array} array - The array to convert.
  29981. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29982. * @return {TypedArray} The converted array.
  29983. */
  29984. function convertArray( array, type ) {
  29985. if ( ! array || array.constructor === type ) return array;
  29986. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29987. return new type( array ); // create typed array
  29988. }
  29989. return Array.prototype.slice.call( array ); // create Array
  29990. }
  29991. /**
  29992. * Returns `true` if the given object is a typed array.
  29993. *
  29994. * @param {any} object - The object to check.
  29995. * @return {boolean} Whether the given object is a typed array.
  29996. */
  29997. function isTypedArray( object ) {
  29998. return ArrayBuffer.isView( object ) && ! ( object instanceof DataView );
  29999. }
  30000. /**
  30001. * Returns an array by which times and values can be sorted.
  30002. *
  30003. * @param {Array<number>} times - The keyframe time values.
  30004. * @return {Array<number>} The array.
  30005. */
  30006. function getKeyframeOrder( times ) {
  30007. function compareTime( i, j ) {
  30008. return times[ i ] - times[ j ];
  30009. }
  30010. const n = times.length;
  30011. const result = new Array( n );
  30012. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30013. result.sort( compareTime );
  30014. return result;
  30015. }
  30016. /**
  30017. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30018. *
  30019. * @param {Array<number>} values - The values to sort.
  30020. * @param {number} stride - The stride.
  30021. * @param {Array<number>} order - The sort order.
  30022. * @return {Array<number>} The sorted values.
  30023. */
  30024. function sortedArray( values, stride, order ) {
  30025. const nValues = values.length;
  30026. const result = new values.constructor( nValues );
  30027. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30028. const srcOffset = order[ i ] * stride;
  30029. for ( let j = 0; j !== stride; ++ j ) {
  30030. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30031. }
  30032. }
  30033. return result;
  30034. }
  30035. /**
  30036. * Used for parsing AOS keyframe formats.
  30037. *
  30038. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30039. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30040. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30041. * @param {string} valuePropertyName - The name of the property to use.
  30042. */
  30043. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30044. let i = 1, key = jsonKeys[ 0 ];
  30045. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30046. key = jsonKeys[ i ++ ];
  30047. }
  30048. if ( key === undefined ) return; // no data
  30049. let value = key[ valuePropertyName ];
  30050. if ( value === undefined ) return; // no data
  30051. if ( Array.isArray( value ) ) {
  30052. do {
  30053. value = key[ valuePropertyName ];
  30054. if ( value !== undefined ) {
  30055. times.push( key.time );
  30056. values.push( ...value ); // push all elements
  30057. }
  30058. key = jsonKeys[ i ++ ];
  30059. } while ( key !== undefined );
  30060. } else if ( value.toArray !== undefined ) {
  30061. // ...assume THREE.Math-ish
  30062. do {
  30063. value = key[ valuePropertyName ];
  30064. if ( value !== undefined ) {
  30065. times.push( key.time );
  30066. value.toArray( values, values.length );
  30067. }
  30068. key = jsonKeys[ i ++ ];
  30069. } while ( key !== undefined );
  30070. } else {
  30071. // otherwise push as-is
  30072. do {
  30073. value = key[ valuePropertyName ];
  30074. if ( value !== undefined ) {
  30075. times.push( key.time );
  30076. values.push( value );
  30077. }
  30078. key = jsonKeys[ i ++ ];
  30079. } while ( key !== undefined );
  30080. }
  30081. }
  30082. /**
  30083. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30084. *
  30085. * @param {AnimationClip} sourceClip - The values to sort.
  30086. * @param {string} name - The name of the clip.
  30087. * @param {number} startFrame - The start frame.
  30088. * @param {number} endFrame - The end frame.
  30089. * @param {number} [fps=30] - The FPS.
  30090. * @return {AnimationClip} The new sub clip.
  30091. */
  30092. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30093. const clip = sourceClip.clone();
  30094. clip.name = name;
  30095. const tracks = [];
  30096. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30097. const track = clip.tracks[ i ];
  30098. const valueSize = track.getValueSize();
  30099. const times = [];
  30100. const values = [];
  30101. for ( let j = 0; j < track.times.length; ++ j ) {
  30102. const frame = track.times[ j ] * fps;
  30103. if ( frame < startFrame || frame >= endFrame ) continue;
  30104. times.push( track.times[ j ] );
  30105. for ( let k = 0; k < valueSize; ++ k ) {
  30106. values.push( track.values[ j * valueSize + k ] );
  30107. }
  30108. }
  30109. if ( times.length === 0 ) continue;
  30110. track.times = convertArray( times, track.times.constructor );
  30111. track.values = convertArray( values, track.values.constructor );
  30112. tracks.push( track );
  30113. }
  30114. clip.tracks = tracks;
  30115. // find minimum .times value across all tracks in the trimmed clip
  30116. let minStartTime = Infinity;
  30117. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30118. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30119. minStartTime = clip.tracks[ i ].times[ 0 ];
  30120. }
  30121. }
  30122. // shift all tracks such that clip begins at t=0
  30123. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30124. clip.tracks[ i ].shift( -1 * minStartTime );
  30125. }
  30126. clip.resetDuration();
  30127. return clip;
  30128. }
  30129. /**
  30130. * Converts the keyframes of the given animation clip to an additive format.
  30131. *
  30132. * @param {AnimationClip} targetClip - The clip to make additive.
  30133. * @param {number} [referenceFrame=0] - The reference frame.
  30134. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30135. * @param {number} [fps=30] - The FPS.
  30136. * @return {AnimationClip} The updated clip which is now additive.
  30137. */
  30138. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30139. if ( fps <= 0 ) fps = 30;
  30140. const numTracks = referenceClip.tracks.length;
  30141. const referenceTime = referenceFrame / fps;
  30142. // Make each track's values relative to the values at the reference frame
  30143. for ( let i = 0; i < numTracks; ++ i ) {
  30144. const referenceTrack = referenceClip.tracks[ i ];
  30145. const referenceTrackType = referenceTrack.ValueTypeName;
  30146. // Skip this track if it's non-numeric
  30147. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30148. // Find the track in the target clip whose name and type matches the reference track
  30149. const targetTrack = targetClip.tracks.find( function ( track ) {
  30150. return track.name === referenceTrack.name
  30151. && track.ValueTypeName === referenceTrackType;
  30152. } );
  30153. if ( targetTrack === undefined ) continue;
  30154. let referenceOffset = 0;
  30155. const referenceValueSize = referenceTrack.getValueSize();
  30156. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30157. referenceOffset = referenceValueSize / 3;
  30158. }
  30159. let targetOffset = 0;
  30160. const targetValueSize = targetTrack.getValueSize();
  30161. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30162. targetOffset = targetValueSize / 3;
  30163. }
  30164. const lastIndex = referenceTrack.times.length - 1;
  30165. let referenceValue;
  30166. // Find the value to subtract out of the track
  30167. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30168. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30169. const startIndex = referenceOffset;
  30170. const endIndex = referenceValueSize - referenceOffset;
  30171. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30172. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30173. // Reference frame is after the last keyframe, so just use the last keyframe
  30174. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30175. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30176. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30177. } else {
  30178. // Interpolate to the reference value
  30179. const interpolant = referenceTrack.createInterpolant();
  30180. const startIndex = referenceOffset;
  30181. const endIndex = referenceValueSize - referenceOffset;
  30182. interpolant.evaluate( referenceTime );
  30183. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30184. }
  30185. // Conjugate the quaternion
  30186. if ( referenceTrackType === 'quaternion' ) {
  30187. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30188. referenceQuat.toArray( referenceValue );
  30189. }
  30190. // Subtract the reference value from all of the track values
  30191. const numTimes = targetTrack.times.length;
  30192. for ( let j = 0; j < numTimes; ++ j ) {
  30193. const valueStart = j * targetValueSize + targetOffset;
  30194. if ( referenceTrackType === 'quaternion' ) {
  30195. // Multiply the conjugate for quaternion track types
  30196. Quaternion.multiplyQuaternionsFlat(
  30197. targetTrack.values,
  30198. valueStart,
  30199. referenceValue,
  30200. 0,
  30201. targetTrack.values,
  30202. valueStart
  30203. );
  30204. } else {
  30205. const valueEnd = targetValueSize - targetOffset * 2;
  30206. // Subtract each value for all other numeric track types
  30207. for ( let k = 0; k < valueEnd; ++ k ) {
  30208. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30209. }
  30210. }
  30211. }
  30212. }
  30213. targetClip.blendMode = AdditiveAnimationBlendMode;
  30214. return targetClip;
  30215. }
  30216. /**
  30217. * A class with various methods to assist with animations.
  30218. *
  30219. * @hideconstructor
  30220. */
  30221. class AnimationUtils {
  30222. /**
  30223. * Converts an array to a specific type
  30224. *
  30225. * @static
  30226. * @param {TypedArray|Array} array - The array to convert.
  30227. * @param {TypedArray.constructor} type - The constructor of a type array.
  30228. * @return {TypedArray} The converted array
  30229. */
  30230. static convertArray( array, type ) {
  30231. return convertArray( array, type );
  30232. }
  30233. /**
  30234. * Returns `true` if the given object is a typed array.
  30235. *
  30236. * @static
  30237. * @param {any} object - The object to check.
  30238. * @return {boolean} Whether the given object is a typed array.
  30239. */
  30240. static isTypedArray( object ) {
  30241. return isTypedArray( object );
  30242. }
  30243. /**
  30244. * Returns an array by which times and values can be sorted.
  30245. *
  30246. * @static
  30247. * @param {Array<number>} times - The keyframe time values.
  30248. * @return {Array<number>} The array.
  30249. */
  30250. static getKeyframeOrder( times ) {
  30251. return getKeyframeOrder( times );
  30252. }
  30253. /**
  30254. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30255. *
  30256. * @static
  30257. * @param {Array<number>} values - The values to sort.
  30258. * @param {number} stride - The stride.
  30259. * @param {Array<number>} order - The sort order.
  30260. * @return {Array<number>} The sorted values.
  30261. */
  30262. static sortedArray( values, stride, order ) {
  30263. return sortedArray( values, stride, order );
  30264. }
  30265. /**
  30266. * Used for parsing AOS keyframe formats.
  30267. *
  30268. * @static
  30269. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30270. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30271. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30272. * @param {string} valuePropertyName - The name of the property to use.
  30273. */
  30274. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30275. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30276. }
  30277. /**
  30278. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30279. *
  30280. * @static
  30281. * @param {AnimationClip} sourceClip - The values to sort.
  30282. * @param {string} name - The name of the clip.
  30283. * @param {number} startFrame - The start frame.
  30284. * @param {number} endFrame - The end frame.
  30285. * @param {number} [fps=30] - The FPS.
  30286. * @return {AnimationClip} The new sub clip.
  30287. */
  30288. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30289. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30290. }
  30291. /**
  30292. * Converts the keyframes of the given animation clip to an additive format.
  30293. *
  30294. * @static
  30295. * @param {AnimationClip} targetClip - The clip to make additive.
  30296. * @param {number} [referenceFrame=0] - The reference frame.
  30297. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30298. * @param {number} [fps=30] - The FPS.
  30299. * @return {AnimationClip} The updated clip which is now additive.
  30300. */
  30301. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30302. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30303. }
  30304. }
  30305. /**
  30306. * Abstract base class of interpolants over parametric samples.
  30307. *
  30308. * The parameter domain is one dimensional, typically the time or a path
  30309. * along a curve defined by the data.
  30310. *
  30311. * The sample values can have any dimensionality and derived classes may
  30312. * apply special interpretations to the data.
  30313. *
  30314. * This class provides the interval seek in a Template Method, deferring
  30315. * the actual interpolation to derived classes.
  30316. *
  30317. * Time complexity is O(1) for linear access crossing at most two points
  30318. * and O(log N) for random access, where N is the number of positions.
  30319. *
  30320. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30321. *
  30322. * @abstract
  30323. */
  30324. class Interpolant {
  30325. /**
  30326. * Constructs a new interpolant.
  30327. *
  30328. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30329. * @param {TypedArray} sampleValues - The sample values.
  30330. * @param {number} sampleSize - The sample size
  30331. * @param {TypedArray} [resultBuffer] - The result buffer.
  30332. */
  30333. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30334. /**
  30335. * The parameter positions.
  30336. *
  30337. * @type {TypedArray}
  30338. */
  30339. this.parameterPositions = parameterPositions;
  30340. /**
  30341. * A cache index.
  30342. *
  30343. * @private
  30344. * @type {number}
  30345. * @default 0
  30346. */
  30347. this._cachedIndex = 0;
  30348. /**
  30349. * The result buffer.
  30350. *
  30351. * @type {TypedArray}
  30352. */
  30353. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30354. /**
  30355. * The sample values.
  30356. *
  30357. * @type {TypedArray}
  30358. */
  30359. this.sampleValues = sampleValues;
  30360. /**
  30361. * The value size.
  30362. *
  30363. * @type {TypedArray}
  30364. */
  30365. this.valueSize = sampleSize;
  30366. /**
  30367. * The interpolation settings.
  30368. *
  30369. * @type {?Object}
  30370. * @default null
  30371. */
  30372. this.settings = null;
  30373. /**
  30374. * The default settings object.
  30375. *
  30376. * @type {Object}
  30377. */
  30378. this.DefaultSettings_ = {};
  30379. }
  30380. /**
  30381. * Evaluate the interpolant at position `t`.
  30382. *
  30383. * @param {number} t - The interpolation factor.
  30384. * @return {TypedArray} The result buffer.
  30385. */
  30386. evaluate( t ) {
  30387. const pp = this.parameterPositions;
  30388. let i1 = this._cachedIndex,
  30389. t1 = pp[ i1 ],
  30390. t0 = pp[ i1 - 1 ];
  30391. validate_interval: {
  30392. seek: {
  30393. let right;
  30394. linear_scan: {
  30395. //- See http://jsperf.com/comparison-to-undefined/3
  30396. //- slower code:
  30397. //-
  30398. //- if ( t >= t1 || t1 === undefined ) {
  30399. forward_scan: if ( ! ( t < t1 ) ) {
  30400. for ( let giveUpAt = i1 + 2; ; ) {
  30401. if ( t1 === undefined ) {
  30402. if ( t < t0 ) break forward_scan;
  30403. // after end
  30404. i1 = pp.length;
  30405. this._cachedIndex = i1;
  30406. return this.copySampleValue_( i1 - 1 );
  30407. }
  30408. if ( i1 === giveUpAt ) break; // this loop
  30409. t0 = t1;
  30410. t1 = pp[ ++ i1 ];
  30411. if ( t < t1 ) {
  30412. // we have arrived at the sought interval
  30413. break seek;
  30414. }
  30415. }
  30416. // prepare binary search on the right side of the index
  30417. right = pp.length;
  30418. break linear_scan;
  30419. }
  30420. //- slower code:
  30421. //- if ( t < t0 || t0 === undefined ) {
  30422. if ( ! ( t >= t0 ) ) {
  30423. // looping?
  30424. const t1global = pp[ 1 ];
  30425. if ( t < t1global ) {
  30426. i1 = 2; // + 1, using the scan for the details
  30427. t0 = t1global;
  30428. }
  30429. // linear reverse scan
  30430. for ( let giveUpAt = i1 - 2; ; ) {
  30431. if ( t0 === undefined ) {
  30432. // before start
  30433. this._cachedIndex = 0;
  30434. return this.copySampleValue_( 0 );
  30435. }
  30436. if ( i1 === giveUpAt ) break; // this loop
  30437. t1 = t0;
  30438. t0 = pp[ -- i1 - 1 ];
  30439. if ( t >= t0 ) {
  30440. // we have arrived at the sought interval
  30441. break seek;
  30442. }
  30443. }
  30444. // prepare binary search on the left side of the index
  30445. right = i1;
  30446. i1 = 0;
  30447. break linear_scan;
  30448. }
  30449. // the interval is valid
  30450. break validate_interval;
  30451. } // linear scan
  30452. // binary search
  30453. while ( i1 < right ) {
  30454. const mid = ( i1 + right ) >>> 1;
  30455. if ( t < pp[ mid ] ) {
  30456. right = mid;
  30457. } else {
  30458. i1 = mid + 1;
  30459. }
  30460. }
  30461. t1 = pp[ i1 ];
  30462. t0 = pp[ i1 - 1 ];
  30463. // check boundary cases, again
  30464. if ( t0 === undefined ) {
  30465. this._cachedIndex = 0;
  30466. return this.copySampleValue_( 0 );
  30467. }
  30468. if ( t1 === undefined ) {
  30469. i1 = pp.length;
  30470. this._cachedIndex = i1;
  30471. return this.copySampleValue_( i1 - 1 );
  30472. }
  30473. } // seek
  30474. this._cachedIndex = i1;
  30475. this.intervalChanged_( i1, t0, t1 );
  30476. } // validate_interval
  30477. return this.interpolate_( i1, t0, t, t1 );
  30478. }
  30479. /**
  30480. * Returns the interpolation settings.
  30481. *
  30482. * @return {Object} The interpolation settings.
  30483. */
  30484. getSettings_() {
  30485. return this.settings || this.DefaultSettings_;
  30486. }
  30487. /**
  30488. * Copies a sample value to the result buffer.
  30489. *
  30490. * @param {number} index - An index into the sample value buffer.
  30491. * @return {TypedArray} The result buffer.
  30492. */
  30493. copySampleValue_( index ) {
  30494. // copies a sample value to the result buffer
  30495. const result = this.resultBuffer,
  30496. values = this.sampleValues,
  30497. stride = this.valueSize,
  30498. offset = index * stride;
  30499. for ( let i = 0; i !== stride; ++ i ) {
  30500. result[ i ] = values[ offset + i ];
  30501. }
  30502. return result;
  30503. }
  30504. /**
  30505. * Copies a sample value to the result buffer.
  30506. *
  30507. * @abstract
  30508. * @param {number} i1 - An index into the sample value buffer.
  30509. * @param {number} t0 - The previous interpolation factor.
  30510. * @param {number} t - The current interpolation factor.
  30511. * @param {number} t1 - The next interpolation factor.
  30512. * @return {TypedArray} The result buffer.
  30513. */
  30514. interpolate_( /* i1, t0, t, t1 */ ) {
  30515. throw new Error( 'call to abstract method' );
  30516. // implementations shall return this.resultBuffer
  30517. }
  30518. /**
  30519. * Optional method that is executed when the interval has changed.
  30520. *
  30521. * @param {number} i1 - An index into the sample value buffer.
  30522. * @param {number} t0 - The previous interpolation factor.
  30523. * @param {number} t - The current interpolation factor.
  30524. */
  30525. intervalChanged_( /* i1, t0, t1 */ ) {
  30526. // empty
  30527. }
  30528. }
  30529. /**
  30530. * Fast and simple cubic spline interpolant.
  30531. *
  30532. * It was derived from a Hermitian construction setting the first derivative
  30533. * at each sample position to the linear slope between neighboring positions
  30534. * over their parameter interval.
  30535. *
  30536. * @augments Interpolant
  30537. */
  30538. class CubicInterpolant extends Interpolant {
  30539. /**
  30540. * Constructs a new cubic interpolant.
  30541. *
  30542. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30543. * @param {TypedArray} sampleValues - The sample values.
  30544. * @param {number} sampleSize - The sample size
  30545. * @param {TypedArray} [resultBuffer] - The result buffer.
  30546. */
  30547. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30548. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30549. this._weightPrev = -0;
  30550. this._offsetPrev = -0;
  30551. this._weightNext = -0;
  30552. this._offsetNext = -0;
  30553. this.DefaultSettings_ = {
  30554. endingStart: ZeroCurvatureEnding,
  30555. endingEnd: ZeroCurvatureEnding
  30556. };
  30557. }
  30558. intervalChanged_( i1, t0, t1 ) {
  30559. const pp = this.parameterPositions;
  30560. let iPrev = i1 - 2,
  30561. iNext = i1 + 1,
  30562. tPrev = pp[ iPrev ],
  30563. tNext = pp[ iNext ];
  30564. if ( tPrev === undefined ) {
  30565. switch ( this.getSettings_().endingStart ) {
  30566. case ZeroSlopeEnding:
  30567. // f'(t0) = 0
  30568. iPrev = i1;
  30569. tPrev = 2 * t0 - t1;
  30570. break;
  30571. case WrapAroundEnding:
  30572. // use the other end of the curve
  30573. iPrev = pp.length - 2;
  30574. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30575. break;
  30576. default: // ZeroCurvatureEnding
  30577. // f''(t0) = 0 a.k.a. Natural Spline
  30578. iPrev = i1;
  30579. tPrev = t1;
  30580. }
  30581. }
  30582. if ( tNext === undefined ) {
  30583. switch ( this.getSettings_().endingEnd ) {
  30584. case ZeroSlopeEnding:
  30585. // f'(tN) = 0
  30586. iNext = i1;
  30587. tNext = 2 * t1 - t0;
  30588. break;
  30589. case WrapAroundEnding:
  30590. // use the other end of the curve
  30591. iNext = 1;
  30592. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30593. break;
  30594. default: // ZeroCurvatureEnding
  30595. // f''(tN) = 0, a.k.a. Natural Spline
  30596. iNext = i1 - 1;
  30597. tNext = t0;
  30598. }
  30599. }
  30600. const halfDt = ( t1 - t0 ) * 0.5,
  30601. stride = this.valueSize;
  30602. this._weightPrev = halfDt / ( t0 - tPrev );
  30603. this._weightNext = halfDt / ( tNext - t1 );
  30604. this._offsetPrev = iPrev * stride;
  30605. this._offsetNext = iNext * stride;
  30606. }
  30607. interpolate_( i1, t0, t, t1 ) {
  30608. const result = this.resultBuffer,
  30609. values = this.sampleValues,
  30610. stride = this.valueSize,
  30611. o1 = i1 * stride, o0 = o1 - stride,
  30612. oP = this._offsetPrev, oN = this._offsetNext,
  30613. wP = this._weightPrev, wN = this._weightNext,
  30614. p = ( t - t0 ) / ( t1 - t0 ),
  30615. pp = p * p,
  30616. ppp = pp * p;
  30617. // evaluate polynomials
  30618. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30619. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30620. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30621. const sN = wN * ppp - wN * pp;
  30622. // combine data linearly
  30623. for ( let i = 0; i !== stride; ++ i ) {
  30624. result[ i ] =
  30625. sP * values[ oP + i ] +
  30626. s0 * values[ o0 + i ] +
  30627. s1 * values[ o1 + i ] +
  30628. sN * values[ oN + i ];
  30629. }
  30630. return result;
  30631. }
  30632. }
  30633. /**
  30634. * A basic linear interpolant.
  30635. *
  30636. * @augments Interpolant
  30637. */
  30638. class LinearInterpolant extends Interpolant {
  30639. /**
  30640. * Constructs a new linear interpolant.
  30641. *
  30642. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30643. * @param {TypedArray} sampleValues - The sample values.
  30644. * @param {number} sampleSize - The sample size
  30645. * @param {TypedArray} [resultBuffer] - The result buffer.
  30646. */
  30647. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30648. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30649. }
  30650. interpolate_( i1, t0, t, t1 ) {
  30651. const result = this.resultBuffer,
  30652. values = this.sampleValues,
  30653. stride = this.valueSize,
  30654. offset1 = i1 * stride,
  30655. offset0 = offset1 - stride,
  30656. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30657. weight0 = 1 - weight1;
  30658. for ( let i = 0; i !== stride; ++ i ) {
  30659. result[ i ] =
  30660. values[ offset0 + i ] * weight0 +
  30661. values[ offset1 + i ] * weight1;
  30662. }
  30663. return result;
  30664. }
  30665. }
  30666. /**
  30667. * Interpolant that evaluates to the sample value at the position preceding
  30668. * the parameter.
  30669. *
  30670. * @augments Interpolant
  30671. */
  30672. class DiscreteInterpolant extends Interpolant {
  30673. /**
  30674. * Constructs a new discrete interpolant.
  30675. *
  30676. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30677. * @param {TypedArray} sampleValues - The sample values.
  30678. * @param {number} sampleSize - The sample size
  30679. * @param {TypedArray} [resultBuffer] - The result buffer.
  30680. */
  30681. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30682. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30683. }
  30684. interpolate_( i1 /*, t0, t, t1 */ ) {
  30685. return this.copySampleValue_( i1 - 1 );
  30686. }
  30687. }
  30688. /**
  30689. * Represents s a timed sequence of keyframes, which are composed of lists of
  30690. * times and related values, and which are used to animate a specific property
  30691. * of an object.
  30692. */
  30693. class KeyframeTrack {
  30694. /**
  30695. * Constructs a new keyframe track.
  30696. *
  30697. * @param {string} name - The keyframe track's name.
  30698. * @param {Array<number>} times - A list of keyframe times.
  30699. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30700. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30701. */
  30702. constructor( name, times, values, interpolation ) {
  30703. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30704. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30705. /**
  30706. * The track's name can refer to morph targets or bones or
  30707. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30708. * for the forms of strings that can be parsed for property binding.
  30709. *
  30710. * @type {string}
  30711. */
  30712. this.name = name;
  30713. /**
  30714. * The keyframe times.
  30715. *
  30716. * @type {Float32Array}
  30717. */
  30718. this.times = convertArray( times, this.TimeBufferType );
  30719. /**
  30720. * The keyframe values.
  30721. *
  30722. * @type {Float32Array}
  30723. */
  30724. this.values = convertArray( values, this.ValueBufferType );
  30725. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30726. }
  30727. /**
  30728. * Converts the keyframe track to JSON.
  30729. *
  30730. * @static
  30731. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30732. * @return {Object} The serialized keyframe track as JSON.
  30733. */
  30734. static toJSON( track ) {
  30735. const trackType = track.constructor;
  30736. let json;
  30737. // derived classes can define a static toJSON method
  30738. if ( trackType.toJSON !== this.toJSON ) {
  30739. json = trackType.toJSON( track );
  30740. } else {
  30741. // by default, we assume the data can be serialized as-is
  30742. json = {
  30743. 'name': track.name,
  30744. 'times': convertArray( track.times, Array ),
  30745. 'values': convertArray( track.values, Array )
  30746. };
  30747. const interpolation = track.getInterpolation();
  30748. if ( interpolation !== track.DefaultInterpolation ) {
  30749. json.interpolation = interpolation;
  30750. }
  30751. }
  30752. json.type = track.ValueTypeName; // mandatory
  30753. return json;
  30754. }
  30755. /**
  30756. * Factory method for creating a new discrete interpolant.
  30757. *
  30758. * @static
  30759. * @param {TypedArray} [result] - The result buffer.
  30760. * @return {DiscreteInterpolant} The new interpolant.
  30761. */
  30762. InterpolantFactoryMethodDiscrete( result ) {
  30763. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30764. }
  30765. /**
  30766. * Factory method for creating a new linear interpolant.
  30767. *
  30768. * @static
  30769. * @param {TypedArray} [result] - The result buffer.
  30770. * @return {LinearInterpolant} The new interpolant.
  30771. */
  30772. InterpolantFactoryMethodLinear( result ) {
  30773. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30774. }
  30775. /**
  30776. * Factory method for creating a new smooth interpolant.
  30777. *
  30778. * @static
  30779. * @param {TypedArray} [result] - The result buffer.
  30780. * @return {CubicInterpolant} The new interpolant.
  30781. */
  30782. InterpolantFactoryMethodSmooth( result ) {
  30783. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30784. }
  30785. /**
  30786. * Defines the interpolation factor method for this keyframe track.
  30787. *
  30788. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  30789. * @return {KeyframeTrack} A reference to this keyframe track.
  30790. */
  30791. setInterpolation( interpolation ) {
  30792. let factoryMethod;
  30793. switch ( interpolation ) {
  30794. case InterpolateDiscrete:
  30795. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30796. break;
  30797. case InterpolateLinear:
  30798. factoryMethod = this.InterpolantFactoryMethodLinear;
  30799. break;
  30800. case InterpolateSmooth:
  30801. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30802. break;
  30803. }
  30804. if ( factoryMethod === undefined ) {
  30805. const message = 'unsupported interpolation for ' +
  30806. this.ValueTypeName + ' keyframe track named ' + this.name;
  30807. if ( this.createInterpolant === undefined ) {
  30808. // fall back to default, unless the default itself is messed up
  30809. if ( interpolation !== this.DefaultInterpolation ) {
  30810. this.setInterpolation( this.DefaultInterpolation );
  30811. } else {
  30812. throw new Error( message ); // fatal, in this case
  30813. }
  30814. }
  30815. console.warn( 'THREE.KeyframeTrack:', message );
  30816. return this;
  30817. }
  30818. this.createInterpolant = factoryMethod;
  30819. return this;
  30820. }
  30821. /**
  30822. * Returns the current interpolation type.
  30823. *
  30824. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  30825. */
  30826. getInterpolation() {
  30827. switch ( this.createInterpolant ) {
  30828. case this.InterpolantFactoryMethodDiscrete:
  30829. return InterpolateDiscrete;
  30830. case this.InterpolantFactoryMethodLinear:
  30831. return InterpolateLinear;
  30832. case this.InterpolantFactoryMethodSmooth:
  30833. return InterpolateSmooth;
  30834. }
  30835. }
  30836. /**
  30837. * Returns the value size.
  30838. *
  30839. * @return {number} The value size.
  30840. */
  30841. getValueSize() {
  30842. return this.values.length / this.times.length;
  30843. }
  30844. /**
  30845. * Moves all keyframes either forward or backward in time.
  30846. *
  30847. * @param {number} timeOffset - The offset to move the time values.
  30848. * @return {KeyframeTrack} A reference to this keyframe track.
  30849. */
  30850. shift( timeOffset ) {
  30851. if ( timeOffset !== 0.0 ) {
  30852. const times = this.times;
  30853. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30854. times[ i ] += timeOffset;
  30855. }
  30856. }
  30857. return this;
  30858. }
  30859. /**
  30860. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30861. *
  30862. * @param {number} timeScale - The time scale.
  30863. * @return {KeyframeTrack} A reference to this keyframe track.
  30864. */
  30865. scale( timeScale ) {
  30866. if ( timeScale !== 1.0 ) {
  30867. const times = this.times;
  30868. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30869. times[ i ] *= timeScale;
  30870. }
  30871. }
  30872. return this;
  30873. }
  30874. /**
  30875. * Removes keyframes before and after animation without changing any values within the defined time range.
  30876. *
  30877. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30878. * keys this will change their values
  30879. *
  30880. * @param {number} startTime - The start time.
  30881. * @param {number} endTime - The end time.
  30882. * @return {KeyframeTrack} A reference to this keyframe track.
  30883. */
  30884. trim( startTime, endTime ) {
  30885. const times = this.times,
  30886. nKeys = times.length;
  30887. let from = 0,
  30888. to = nKeys - 1;
  30889. while ( from !== nKeys && times[ from ] < startTime ) {
  30890. ++ from;
  30891. }
  30892. while ( to !== -1 && times[ to ] > endTime ) {
  30893. -- to;
  30894. }
  30895. ++ to; // inclusive -> exclusive bound
  30896. if ( from !== 0 || to !== nKeys ) {
  30897. // empty tracks are forbidden, so keep at least one keyframe
  30898. if ( from >= to ) {
  30899. to = Math.max( to, 1 );
  30900. from = to - 1;
  30901. }
  30902. const stride = this.getValueSize();
  30903. this.times = times.slice( from, to );
  30904. this.values = this.values.slice( from * stride, to * stride );
  30905. }
  30906. return this;
  30907. }
  30908. /**
  30909. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30910. * are valid.
  30911. *
  30912. * @return {boolean} Whether the keyframes are valid or not.
  30913. */
  30914. validate() {
  30915. let valid = true;
  30916. const valueSize = this.getValueSize();
  30917. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30918. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  30919. valid = false;
  30920. }
  30921. const times = this.times,
  30922. values = this.values,
  30923. nKeys = times.length;
  30924. if ( nKeys === 0 ) {
  30925. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  30926. valid = false;
  30927. }
  30928. let prevTime = null;
  30929. for ( let i = 0; i !== nKeys; i ++ ) {
  30930. const currTime = times[ i ];
  30931. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30932. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30933. valid = false;
  30934. break;
  30935. }
  30936. if ( prevTime !== null && prevTime > currTime ) {
  30937. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30938. valid = false;
  30939. break;
  30940. }
  30941. prevTime = currTime;
  30942. }
  30943. if ( values !== undefined ) {
  30944. if ( isTypedArray( values ) ) {
  30945. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30946. const value = values[ i ];
  30947. if ( isNaN( value ) ) {
  30948. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  30949. valid = false;
  30950. break;
  30951. }
  30952. }
  30953. }
  30954. }
  30955. return valid;
  30956. }
  30957. /**
  30958. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30959. * common in morph target sequences).
  30960. *
  30961. * @return {AnimationClip} A reference to this animation clip.
  30962. */
  30963. optimize() {
  30964. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30965. // times or values may be shared with other tracks, so overwriting is unsafe
  30966. const times = this.times.slice(),
  30967. values = this.values.slice(),
  30968. stride = this.getValueSize(),
  30969. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30970. lastIndex = times.length - 1;
  30971. let writeIndex = 1;
  30972. for ( let i = 1; i < lastIndex; ++ i ) {
  30973. let keep = false;
  30974. const time = times[ i ];
  30975. const timeNext = times[ i + 1 ];
  30976. // remove adjacent keyframes scheduled at the same time
  30977. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30978. if ( ! smoothInterpolation ) {
  30979. // remove unnecessary keyframes same as their neighbors
  30980. const offset = i * stride,
  30981. offsetP = offset - stride,
  30982. offsetN = offset + stride;
  30983. for ( let j = 0; j !== stride; ++ j ) {
  30984. const value = values[ offset + j ];
  30985. if ( value !== values[ offsetP + j ] ||
  30986. value !== values[ offsetN + j ] ) {
  30987. keep = true;
  30988. break;
  30989. }
  30990. }
  30991. } else {
  30992. keep = true;
  30993. }
  30994. }
  30995. // in-place compaction
  30996. if ( keep ) {
  30997. if ( i !== writeIndex ) {
  30998. times[ writeIndex ] = times[ i ];
  30999. const readOffset = i * stride,
  31000. writeOffset = writeIndex * stride;
  31001. for ( let j = 0; j !== stride; ++ j ) {
  31002. values[ writeOffset + j ] = values[ readOffset + j ];
  31003. }
  31004. }
  31005. ++ writeIndex;
  31006. }
  31007. }
  31008. // flush last keyframe (compaction looks ahead)
  31009. if ( lastIndex > 0 ) {
  31010. times[ writeIndex ] = times[ lastIndex ];
  31011. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31012. values[ writeOffset + j ] = values[ readOffset + j ];
  31013. }
  31014. ++ writeIndex;
  31015. }
  31016. if ( writeIndex !== times.length ) {
  31017. this.times = times.slice( 0, writeIndex );
  31018. this.values = values.slice( 0, writeIndex * stride );
  31019. } else {
  31020. this.times = times;
  31021. this.values = values;
  31022. }
  31023. return this;
  31024. }
  31025. /**
  31026. * Returns a new keyframe track with copied values from this instance.
  31027. *
  31028. * @return {KeyframeTrack} A clone of this instance.
  31029. */
  31030. clone() {
  31031. const times = this.times.slice();
  31032. const values = this.values.slice();
  31033. const TypedKeyframeTrack = this.constructor;
  31034. const track = new TypedKeyframeTrack( this.name, times, values );
  31035. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31036. track.createInterpolant = this.createInterpolant;
  31037. return track;
  31038. }
  31039. }
  31040. /**
  31041. * The value type name.
  31042. *
  31043. * @type {String}
  31044. * @default ''
  31045. */
  31046. KeyframeTrack.prototype.ValueTypeName = '';
  31047. /**
  31048. * The time buffer type of this keyframe track.
  31049. *
  31050. * @type {TypedArray|Array}
  31051. * @default Float32Array.constructor
  31052. */
  31053. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31054. /**
  31055. * The value buffer type of this keyframe track.
  31056. *
  31057. * @type {TypedArray|Array}
  31058. * @default Float32Array.constructor
  31059. */
  31060. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31061. /**
  31062. * The default interpolation type of this keyframe track.
  31063. *
  31064. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31065. * @default InterpolateLinear
  31066. */
  31067. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31068. /**
  31069. * A track for boolean keyframe values.
  31070. *
  31071. * @augments KeyframeTrack
  31072. */
  31073. class BooleanKeyframeTrack extends KeyframeTrack {
  31074. /**
  31075. * Constructs a new boolean keyframe track.
  31076. *
  31077. * This keyframe track type has no `interpolation` parameter because the
  31078. * interpolation is always discrete.
  31079. *
  31080. * @param {string} name - The keyframe track's name.
  31081. * @param {Array<number>} times - A list of keyframe times.
  31082. * @param {Array<boolean>} values - A list of keyframe values.
  31083. */
  31084. constructor( name, times, values ) {
  31085. super( name, times, values );
  31086. }
  31087. }
  31088. /**
  31089. * The value type name.
  31090. *
  31091. * @type {String}
  31092. * @default 'bool'
  31093. */
  31094. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31095. /**
  31096. * The value buffer type of this keyframe track.
  31097. *
  31098. * @type {TypedArray|Array}
  31099. * @default Array.constructor
  31100. */
  31101. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31102. /**
  31103. * The default interpolation type of this keyframe track.
  31104. *
  31105. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31106. * @default InterpolateDiscrete
  31107. */
  31108. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31109. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31110. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31111. /**
  31112. * A track for color keyframe values.
  31113. *
  31114. * @augments KeyframeTrack
  31115. */
  31116. class ColorKeyframeTrack extends KeyframeTrack {
  31117. /**
  31118. * Constructs a new color keyframe track.
  31119. *
  31120. * @param {string} name - The keyframe track's name.
  31121. * @param {Array<number>} times - A list of keyframe times.
  31122. * @param {Array<number>} values - A list of keyframe values.
  31123. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31124. */
  31125. constructor( name, times, values, interpolation ) {
  31126. super( name, times, values, interpolation );
  31127. }
  31128. }
  31129. /**
  31130. * The value type name.
  31131. *
  31132. * @type {String}
  31133. * @default 'color'
  31134. */
  31135. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31136. /**
  31137. * A track for numeric keyframe values.
  31138. *
  31139. * @augments KeyframeTrack
  31140. */
  31141. class NumberKeyframeTrack extends KeyframeTrack {
  31142. /**
  31143. * Constructs a new number keyframe track.
  31144. *
  31145. * @param {string} name - The keyframe track's name.
  31146. * @param {Array<number>} times - A list of keyframe times.
  31147. * @param {Array<number>} values - A list of keyframe values.
  31148. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31149. */
  31150. constructor( name, times, values, interpolation ) {
  31151. super( name, times, values, interpolation );
  31152. }
  31153. }
  31154. /**
  31155. * The value type name.
  31156. *
  31157. * @type {String}
  31158. * @default 'number'
  31159. */
  31160. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31161. /**
  31162. * Spherical linear unit quaternion interpolant.
  31163. *
  31164. * @augments Interpolant
  31165. */
  31166. class QuaternionLinearInterpolant extends Interpolant {
  31167. /**
  31168. * Constructs a new SLERP interpolant.
  31169. *
  31170. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31171. * @param {TypedArray} sampleValues - The sample values.
  31172. * @param {number} sampleSize - The sample size
  31173. * @param {TypedArray} [resultBuffer] - The result buffer.
  31174. */
  31175. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31176. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31177. }
  31178. interpolate_( i1, t0, t, t1 ) {
  31179. const result = this.resultBuffer,
  31180. values = this.sampleValues,
  31181. stride = this.valueSize,
  31182. alpha = ( t - t0 ) / ( t1 - t0 );
  31183. let offset = i1 * stride;
  31184. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31185. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31186. }
  31187. return result;
  31188. }
  31189. }
  31190. /**
  31191. * A track for Quaternion keyframe values.
  31192. *
  31193. * @augments KeyframeTrack
  31194. */
  31195. class QuaternionKeyframeTrack extends KeyframeTrack {
  31196. /**
  31197. * Constructs a new Quaternion keyframe track.
  31198. *
  31199. * @param {string} name - The keyframe track's name.
  31200. * @param {Array<number>} times - A list of keyframe times.
  31201. * @param {Array<number>} values - A list of keyframe values.
  31202. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31203. */
  31204. constructor( name, times, values, interpolation ) {
  31205. super( name, times, values, interpolation );
  31206. }
  31207. /**
  31208. * Overwritten so the method returns Quaternion based interpolant.
  31209. *
  31210. * @static
  31211. * @param {TypedArray} [result] - The result buffer.
  31212. * @return {QuaternionLinearInterpolant} The new interpolant.
  31213. */
  31214. InterpolantFactoryMethodLinear( result ) {
  31215. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31216. }
  31217. }
  31218. /**
  31219. * The value type name.
  31220. *
  31221. * @type {String}
  31222. * @default 'quaternion'
  31223. */
  31224. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31225. // ValueBufferType is inherited
  31226. // DefaultInterpolation is inherited;
  31227. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31228. /**
  31229. * A track for string keyframe values.
  31230. *
  31231. * @augments KeyframeTrack
  31232. */
  31233. class StringKeyframeTrack extends KeyframeTrack {
  31234. /**
  31235. * Constructs a new string keyframe track.
  31236. *
  31237. * This keyframe track type has no `interpolation` parameter because the
  31238. * interpolation is always discrete.
  31239. *
  31240. * @param {string} name - The keyframe track's name.
  31241. * @param {Array<number>} times - A list of keyframe times.
  31242. * @param {Array<string>} values - A list of keyframe values.
  31243. */
  31244. constructor( name, times, values ) {
  31245. super( name, times, values );
  31246. }
  31247. }
  31248. /**
  31249. * The value type name.
  31250. *
  31251. * @type {String}
  31252. * @default 'string'
  31253. */
  31254. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31255. /**
  31256. * The value buffer type of this keyframe track.
  31257. *
  31258. * @type {TypedArray|Array}
  31259. * @default Array.constructor
  31260. */
  31261. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31262. /**
  31263. * The default interpolation type of this keyframe track.
  31264. *
  31265. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31266. * @default InterpolateDiscrete
  31267. */
  31268. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31269. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31270. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31271. /**
  31272. * A track for vector keyframe values.
  31273. *
  31274. * @augments KeyframeTrack
  31275. */
  31276. class VectorKeyframeTrack extends KeyframeTrack {
  31277. /**
  31278. * Constructs a new vector keyframe track.
  31279. *
  31280. * @param {string} name - The keyframe track's name.
  31281. * @param {Array<number>} times - A list of keyframe times.
  31282. * @param {Array<number>} values - A list of keyframe values.
  31283. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31284. */
  31285. constructor( name, times, values, interpolation ) {
  31286. super( name, times, values, interpolation );
  31287. }
  31288. }
  31289. /**
  31290. * The value type name.
  31291. *
  31292. * @type {String}
  31293. * @default 'vector'
  31294. */
  31295. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31296. /**
  31297. * A reusable set of keyframe tracks which represent an animation.
  31298. */
  31299. class AnimationClip {
  31300. /**
  31301. * Constructs a new animation clip.
  31302. *
  31303. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31304. * use the static interface of this class for creating clips. In most cases though, animation clips
  31305. * will automatically be created by loaders when importing animated 3D assets.
  31306. *
  31307. * @param {string} [name=''] - The clip's name.
  31308. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31309. * the duration will be calculated from the passed keyframes.
  31310. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31311. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31312. * is blended/combined when two or more animations are simultaneously played.
  31313. */
  31314. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31315. /**
  31316. * The clip's name.
  31317. *
  31318. * @type {string}
  31319. */
  31320. this.name = name;
  31321. /**
  31322. * An array of keyframe tracks.
  31323. *
  31324. * @type {Array<KeyframeTrack>}
  31325. */
  31326. this.tracks = tracks;
  31327. /**
  31328. * The clip's duration in seconds.
  31329. *
  31330. * @type {number}
  31331. */
  31332. this.duration = duration;
  31333. /**
  31334. * Defines how the animation is blended/combined when two or more animations
  31335. * are simultaneously played.
  31336. *
  31337. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31338. */
  31339. this.blendMode = blendMode;
  31340. /**
  31341. * The UUID of the animation clip.
  31342. *
  31343. * @type {string}
  31344. * @readonly
  31345. */
  31346. this.uuid = generateUUID();
  31347. /**
  31348. * An object that can be used to store custom data about the animation clip.
  31349. * It should not hold references to functions as these will not be cloned.
  31350. *
  31351. * @type {Object}
  31352. */
  31353. this.userData = {};
  31354. // this means it should figure out its duration by scanning the tracks
  31355. if ( this.duration < 0 ) {
  31356. this.resetDuration();
  31357. }
  31358. }
  31359. /**
  31360. * Factory method for creating an animation clip from the given JSON.
  31361. *
  31362. * @static
  31363. * @param {Object} json - The serialized animation clip.
  31364. * @return {AnimationClip} The new animation clip.
  31365. */
  31366. static parse( json ) {
  31367. const tracks = [],
  31368. jsonTracks = json.tracks,
  31369. frameTime = 1.0 / ( json.fps || 1.0 );
  31370. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31371. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31372. }
  31373. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31374. clip.uuid = json.uuid;
  31375. clip.userData = JSON.parse( json.userData || '{}' );
  31376. return clip;
  31377. }
  31378. /**
  31379. * Serializes the given animation clip into JSON.
  31380. *
  31381. * @static
  31382. * @param {AnimationClip} clip - The animation clip to serialize.
  31383. * @return {Object} The JSON object.
  31384. */
  31385. static toJSON( clip ) {
  31386. const tracks = [],
  31387. clipTracks = clip.tracks;
  31388. const json = {
  31389. 'name': clip.name,
  31390. 'duration': clip.duration,
  31391. 'tracks': tracks,
  31392. 'uuid': clip.uuid,
  31393. 'blendMode': clip.blendMode,
  31394. 'userData': JSON.stringify( clip.userData ),
  31395. };
  31396. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31397. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31398. }
  31399. return json;
  31400. }
  31401. /**
  31402. * Returns a new animation clip from the passed morph targets array of a
  31403. * geometry, taking a name and the number of frames per second.
  31404. *
  31405. * Note: The fps parameter is required, but the animation speed can be
  31406. * overridden via {@link AnimationAction#setDuration}.
  31407. *
  31408. * @static
  31409. * @param {string} name - The name of the animation clip.
  31410. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31411. * @param {number} fps - The Frames-Per-Second value.
  31412. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31413. * @return {AnimationClip} The new animation clip.
  31414. */
  31415. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31416. const numMorphTargets = morphTargetSequence.length;
  31417. const tracks = [];
  31418. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31419. let times = [];
  31420. let values = [];
  31421. times.push(
  31422. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31423. i,
  31424. ( i + 1 ) % numMorphTargets );
  31425. values.push( 0, 1, 0 );
  31426. const order = getKeyframeOrder( times );
  31427. times = sortedArray( times, 1, order );
  31428. values = sortedArray( values, 1, order );
  31429. // if there is a key at the first frame, duplicate it as the
  31430. // last frame as well for perfect loop.
  31431. if ( ! noLoop && times[ 0 ] === 0 ) {
  31432. times.push( numMorphTargets );
  31433. values.push( values[ 0 ] );
  31434. }
  31435. tracks.push(
  31436. new NumberKeyframeTrack(
  31437. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31438. times, values
  31439. ).scale( 1.0 / fps ) );
  31440. }
  31441. return new this( name, -1, tracks );
  31442. }
  31443. /**
  31444. * Searches for an animation clip by name, taking as its first parameter
  31445. * either an array of clips, or a mesh or geometry that contains an
  31446. * array named "animations" property.
  31447. *
  31448. * @static
  31449. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31450. * @param {string} name - The name to search for.
  31451. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31452. */
  31453. static findByName( objectOrClipArray, name ) {
  31454. let clipArray = objectOrClipArray;
  31455. if ( ! Array.isArray( objectOrClipArray ) ) {
  31456. const o = objectOrClipArray;
  31457. clipArray = o.geometry && o.geometry.animations || o.animations;
  31458. }
  31459. for ( let i = 0; i < clipArray.length; i ++ ) {
  31460. if ( clipArray[ i ].name === name ) {
  31461. return clipArray[ i ];
  31462. }
  31463. }
  31464. return null;
  31465. }
  31466. /**
  31467. * Returns an array of new AnimationClips created from the morph target
  31468. * sequences of a geometry, trying to sort morph target names into
  31469. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31470. *
  31471. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31472. *
  31473. * @static
  31474. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31475. * @param {number} fps - The Frames-Per-Second value.
  31476. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31477. * @return {Array<AnimationClip>} An array of new animation clips.
  31478. */
  31479. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31480. const animationToMorphTargets = {};
  31481. // tested with https://regex101.com/ on trick sequences
  31482. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31483. const pattern = /^([\w-]*?)([\d]+)$/;
  31484. // sort morph target names into animation groups based
  31485. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31486. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31487. const morphTarget = morphTargets[ i ];
  31488. const parts = morphTarget.name.match( pattern );
  31489. if ( parts && parts.length > 1 ) {
  31490. const name = parts[ 1 ];
  31491. let animationMorphTargets = animationToMorphTargets[ name ];
  31492. if ( ! animationMorphTargets ) {
  31493. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31494. }
  31495. animationMorphTargets.push( morphTarget );
  31496. }
  31497. }
  31498. const clips = [];
  31499. for ( const name in animationToMorphTargets ) {
  31500. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31501. }
  31502. return clips;
  31503. }
  31504. /**
  31505. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31506. *
  31507. * @static
  31508. * @deprecated since r175.
  31509. * @param {Object} animation - A serialized animation clip as JSON.
  31510. * @param {Array<Bones>} bones - An array of bones.
  31511. * @return {?AnimationClip} The new animation clip.
  31512. */
  31513. static parseAnimation( animation, bones ) {
  31514. console.warn( 'THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31515. if ( ! animation ) {
  31516. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  31517. return null;
  31518. }
  31519. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31520. // only return track if there are actually keys.
  31521. if ( animationKeys.length !== 0 ) {
  31522. const times = [];
  31523. const values = [];
  31524. flattenJSON( animationKeys, times, values, propertyName );
  31525. // empty keys are filtered out, so check again
  31526. if ( times.length !== 0 ) {
  31527. destTracks.push( new trackType( trackName, times, values ) );
  31528. }
  31529. }
  31530. };
  31531. const tracks = [];
  31532. const clipName = animation.name || 'default';
  31533. const fps = animation.fps || 30;
  31534. const blendMode = animation.blendMode;
  31535. // automatic length determination in AnimationClip.
  31536. let duration = animation.length || -1;
  31537. const hierarchyTracks = animation.hierarchy || [];
  31538. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31539. const animationKeys = hierarchyTracks[ h ].keys;
  31540. // skip empty tracks
  31541. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31542. // process morph targets
  31543. if ( animationKeys[ 0 ].morphTargets ) {
  31544. // figure out all morph targets used in this track
  31545. const morphTargetNames = {};
  31546. let k;
  31547. for ( k = 0; k < animationKeys.length; k ++ ) {
  31548. if ( animationKeys[ k ].morphTargets ) {
  31549. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31550. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31551. }
  31552. }
  31553. }
  31554. // create a track for each morph target with all zero
  31555. // morphTargetInfluences except for the keys in which
  31556. // the morphTarget is named.
  31557. for ( const morphTargetName in morphTargetNames ) {
  31558. const times = [];
  31559. const values = [];
  31560. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31561. const animationKey = animationKeys[ k ];
  31562. times.push( animationKey.time );
  31563. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31564. }
  31565. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31566. }
  31567. duration = morphTargetNames.length * fps;
  31568. } else {
  31569. // ...assume skeletal animation
  31570. const boneName = '.bones[' + bones[ h ].name + ']';
  31571. addNonemptyTrack(
  31572. VectorKeyframeTrack, boneName + '.position',
  31573. animationKeys, 'pos', tracks );
  31574. addNonemptyTrack(
  31575. QuaternionKeyframeTrack, boneName + '.quaternion',
  31576. animationKeys, 'rot', tracks );
  31577. addNonemptyTrack(
  31578. VectorKeyframeTrack, boneName + '.scale',
  31579. animationKeys, 'scl', tracks );
  31580. }
  31581. }
  31582. if ( tracks.length === 0 ) {
  31583. return null;
  31584. }
  31585. const clip = new this( clipName, duration, tracks, blendMode );
  31586. return clip;
  31587. }
  31588. /**
  31589. * Sets the duration of this clip to the duration of its longest keyframe track.
  31590. *
  31591. * @return {AnimationClip} A reference to this animation clip.
  31592. */
  31593. resetDuration() {
  31594. const tracks = this.tracks;
  31595. let duration = 0;
  31596. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31597. const track = this.tracks[ i ];
  31598. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31599. }
  31600. this.duration = duration;
  31601. return this;
  31602. }
  31603. /**
  31604. * Trims all tracks to the clip's duration.
  31605. *
  31606. * @return {AnimationClip} A reference to this animation clip.
  31607. */
  31608. trim() {
  31609. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31610. this.tracks[ i ].trim( 0, this.duration );
  31611. }
  31612. return this;
  31613. }
  31614. /**
  31615. * Performs minimal validation on each track in the clip. Returns `true` if all
  31616. * tracks are valid.
  31617. *
  31618. * @return {boolean} Whether the clip's keyframes are valid or not.
  31619. */
  31620. validate() {
  31621. let valid = true;
  31622. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31623. valid = valid && this.tracks[ i ].validate();
  31624. }
  31625. return valid;
  31626. }
  31627. /**
  31628. * Optimizes each track by removing equivalent sequential keys (which are
  31629. * common in morph target sequences).
  31630. *
  31631. * @return {AnimationClip} A reference to this animation clip.
  31632. */
  31633. optimize() {
  31634. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31635. this.tracks[ i ].optimize();
  31636. }
  31637. return this;
  31638. }
  31639. /**
  31640. * Returns a new animation clip with copied values from this instance.
  31641. *
  31642. * @return {AnimationClip} A clone of this instance.
  31643. */
  31644. clone() {
  31645. const tracks = [];
  31646. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31647. tracks.push( this.tracks[ i ].clone() );
  31648. }
  31649. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31650. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31651. return clip;
  31652. }
  31653. /**
  31654. * Serializes this animation clip into JSON.
  31655. *
  31656. * @return {Object} The JSON object.
  31657. */
  31658. toJSON() {
  31659. return this.constructor.toJSON( this );
  31660. }
  31661. }
  31662. function getTrackTypeForValueTypeName( typeName ) {
  31663. switch ( typeName.toLowerCase() ) {
  31664. case 'scalar':
  31665. case 'double':
  31666. case 'float':
  31667. case 'number':
  31668. case 'integer':
  31669. return NumberKeyframeTrack;
  31670. case 'vector':
  31671. case 'vector2':
  31672. case 'vector3':
  31673. case 'vector4':
  31674. return VectorKeyframeTrack;
  31675. case 'color':
  31676. return ColorKeyframeTrack;
  31677. case 'quaternion':
  31678. return QuaternionKeyframeTrack;
  31679. case 'bool':
  31680. case 'boolean':
  31681. return BooleanKeyframeTrack;
  31682. case 'string':
  31683. return StringKeyframeTrack;
  31684. }
  31685. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31686. }
  31687. function parseKeyframeTrack( json ) {
  31688. if ( json.type === undefined ) {
  31689. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31690. }
  31691. const trackType = getTrackTypeForValueTypeName( json.type );
  31692. if ( json.times === undefined ) {
  31693. const times = [], values = [];
  31694. flattenJSON( json.keys, times, values, 'value' );
  31695. json.times = times;
  31696. json.values = values;
  31697. }
  31698. // derived classes can define a static parse method
  31699. if ( trackType.parse !== undefined ) {
  31700. return trackType.parse( json );
  31701. } else {
  31702. // by default, we assume a constructor compatible with the base
  31703. return new trackType( json.name, json.times, json.values, json.interpolation );
  31704. }
  31705. }
  31706. /**
  31707. * @class
  31708. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31709. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31710. * @hideconstructor
  31711. */
  31712. const Cache = {
  31713. /**
  31714. * Whether caching is enabled or not.
  31715. *
  31716. * @static
  31717. * @type {boolean}
  31718. * @default false
  31719. */
  31720. enabled: false,
  31721. /**
  31722. * A dictionary that holds cached files.
  31723. *
  31724. * @static
  31725. * @type {Object<string,Object>}
  31726. */
  31727. files: {},
  31728. /**
  31729. * Adds a cache entry with a key to reference the file. If this key already
  31730. * holds a file, it is overwritten.
  31731. *
  31732. * @static
  31733. * @param {string} key - The key to reference the cached file.
  31734. * @param {Object} file - The file to be cached.
  31735. */
  31736. add: function ( key, file ) {
  31737. if ( this.enabled === false ) return;
  31738. // console.log( 'THREE.Cache', 'Adding key:', key );
  31739. this.files[ key ] = file;
  31740. },
  31741. /**
  31742. * Gets the cached value for the given key.
  31743. *
  31744. * @static
  31745. * @param {string} key - The key to reference the cached file.
  31746. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31747. */
  31748. get: function ( key ) {
  31749. if ( this.enabled === false ) return;
  31750. // console.log( 'THREE.Cache', 'Checking key:', key );
  31751. return this.files[ key ];
  31752. },
  31753. /**
  31754. * Removes the cached file associated with the given key.
  31755. *
  31756. * @static
  31757. * @param {string} key - The key to reference the cached file.
  31758. */
  31759. remove: function ( key ) {
  31760. delete this.files[ key ];
  31761. },
  31762. /**
  31763. * Remove all values from the cache.
  31764. *
  31765. * @static
  31766. */
  31767. clear: function () {
  31768. this.files = {};
  31769. }
  31770. };
  31771. /**
  31772. * Handles and keeps track of loaded and pending data. A default global
  31773. * instance of this class is created and used by loaders if not supplied
  31774. * manually.
  31775. *
  31776. * In general that should be sufficient, however there are times when it can
  31777. * be useful to have separate loaders - for example if you want to show
  31778. * separate loading bars for objects and textures.
  31779. *
  31780. * ```js
  31781. * const manager = new THREE.LoadingManager();
  31782. * manager.onLoad = () => console.log( 'Loading complete!' );
  31783. *
  31784. * const loader1 = new OBJLoader( manager );
  31785. * const loader2 = new ColladaLoader( manager );
  31786. * ```
  31787. */
  31788. class LoadingManager {
  31789. /**
  31790. * Constructs a new loading manager.
  31791. *
  31792. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31793. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31794. * @param {Function} [onError] - Executes when an error occurs.
  31795. */
  31796. constructor( onLoad, onProgress, onError ) {
  31797. const scope = this;
  31798. let isLoading = false;
  31799. let itemsLoaded = 0;
  31800. let itemsTotal = 0;
  31801. let urlModifier = undefined;
  31802. const handlers = [];
  31803. // Refer to #5689 for the reason why we don't set .onStart
  31804. // in the constructor
  31805. /**
  31806. * Executes when an item starts loading.
  31807. *
  31808. * @type {Function|undefined}
  31809. * @default undefined
  31810. */
  31811. this.onStart = undefined;
  31812. /**
  31813. * Executes when all items have been loaded.
  31814. *
  31815. * @type {Function|undefined}
  31816. * @default undefined
  31817. */
  31818. this.onLoad = onLoad;
  31819. /**
  31820. * Executes when single items have been loaded.
  31821. *
  31822. * @type {Function|undefined}
  31823. * @default undefined
  31824. */
  31825. this.onProgress = onProgress;
  31826. /**
  31827. * Executes when an error occurs.
  31828. *
  31829. * @type {Function|undefined}
  31830. * @default undefined
  31831. */
  31832. this.onError = onError;
  31833. /**
  31834. * Used for aborting ongoing requests in loaders using this manager.
  31835. *
  31836. * @type {AbortController}
  31837. */
  31838. this.abortController = new AbortController();
  31839. /**
  31840. * This should be called by any loader using the manager when the loader
  31841. * starts loading an item.
  31842. *
  31843. * @param {string} url - The URL to load.
  31844. */
  31845. this.itemStart = function ( url ) {
  31846. itemsTotal ++;
  31847. if ( isLoading === false ) {
  31848. if ( scope.onStart !== undefined ) {
  31849. scope.onStart( url, itemsLoaded, itemsTotal );
  31850. }
  31851. }
  31852. isLoading = true;
  31853. };
  31854. /**
  31855. * This should be called by any loader using the manager when the loader
  31856. * ended loading an item.
  31857. *
  31858. * @param {string} url - The URL of the loaded item.
  31859. */
  31860. this.itemEnd = function ( url ) {
  31861. itemsLoaded ++;
  31862. if ( scope.onProgress !== undefined ) {
  31863. scope.onProgress( url, itemsLoaded, itemsTotal );
  31864. }
  31865. if ( itemsLoaded === itemsTotal ) {
  31866. isLoading = false;
  31867. if ( scope.onLoad !== undefined ) {
  31868. scope.onLoad();
  31869. }
  31870. }
  31871. };
  31872. /**
  31873. * This should be called by any loader using the manager when the loader
  31874. * encounters an error when loading an item.
  31875. *
  31876. * @param {string} url - The URL of the item that produces an error.
  31877. */
  31878. this.itemError = function ( url ) {
  31879. if ( scope.onError !== undefined ) {
  31880. scope.onError( url );
  31881. }
  31882. };
  31883. /**
  31884. * Given a URL, uses the URL modifier callback (if any) and returns a
  31885. * resolved URL. If no URL modifier is set, returns the original URL.
  31886. *
  31887. * @param {string} url - The URL to load.
  31888. * @return {string} The resolved URL.
  31889. */
  31890. this.resolveURL = function ( url ) {
  31891. if ( urlModifier ) {
  31892. return urlModifier( url );
  31893. }
  31894. return url;
  31895. };
  31896. /**
  31897. * If provided, the callback will be passed each resource URL before a
  31898. * request is sent. The callback may return the original URL, or a new URL to
  31899. * override loading behavior. This behavior can be used to load assets from
  31900. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31901. *
  31902. * ```js
  31903. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31904. *
  31905. * const manager = new THREE.LoadingManager();
  31906. *
  31907. * // Initialize loading manager with URL callback.
  31908. * const objectURLs = [];
  31909. * manager.setURLModifier( ( url ) => {
  31910. *
  31911. * url = URL.createObjectURL( blobs[ url ] );
  31912. * objectURLs.push( url );
  31913. * return url;
  31914. *
  31915. * } );
  31916. *
  31917. * // Load as usual, then revoke the blob URLs.
  31918. * const loader = new GLTFLoader( manager );
  31919. * loader.load( 'fish.gltf', (gltf) => {
  31920. *
  31921. * scene.add( gltf.scene );
  31922. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31923. *
  31924. * } );
  31925. * ```
  31926. *
  31927. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31928. * @return {LoadingManager} A reference to this loading manager.
  31929. */
  31930. this.setURLModifier = function ( transform ) {
  31931. urlModifier = transform;
  31932. return this;
  31933. };
  31934. /**
  31935. * Registers a loader with the given regular expression. Can be used to
  31936. * define what loader should be used in order to load specific files. A
  31937. * typical use case is to overwrite the default loader for textures.
  31938. *
  31939. * ```js
  31940. * // add handler for TGA textures
  31941. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31942. * ```
  31943. *
  31944. * @param {string} regex - A regular expression.
  31945. * @param {Loader} loader - A loader that should handle matched cases.
  31946. * @return {LoadingManager} A reference to this loading manager.
  31947. */
  31948. this.addHandler = function ( regex, loader ) {
  31949. handlers.push( regex, loader );
  31950. return this;
  31951. };
  31952. /**
  31953. * Removes the loader for the given regular expression.
  31954. *
  31955. * @param {string} regex - A regular expression.
  31956. * @return {LoadingManager} A reference to this loading manager.
  31957. */
  31958. this.removeHandler = function ( regex ) {
  31959. const index = handlers.indexOf( regex );
  31960. if ( index !== -1 ) {
  31961. handlers.splice( index, 2 );
  31962. }
  31963. return this;
  31964. };
  31965. /**
  31966. * Can be used to retrieve the registered loader for the given file path.
  31967. *
  31968. * @param {string} file - The file path.
  31969. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31970. */
  31971. this.getHandler = function ( file ) {
  31972. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31973. const regex = handlers[ i ];
  31974. const loader = handlers[ i + 1 ];
  31975. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31976. if ( regex.test( file ) ) {
  31977. return loader;
  31978. }
  31979. }
  31980. return null;
  31981. };
  31982. /**
  31983. * Can be used to abort ongoing loading requests in loaders using this manager.
  31984. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  31985. * is supported in the browser.
  31986. *
  31987. * @return {LoadingManager} A reference to this loading manager.
  31988. */
  31989. this.abort = function () {
  31990. this.abortController.abort();
  31991. this.abortController = new AbortController();
  31992. return this;
  31993. };
  31994. }
  31995. }
  31996. /**
  31997. * The global default loading manager.
  31998. *
  31999. * @constant
  32000. * @type {LoadingManager}
  32001. */
  32002. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32003. /**
  32004. * Abstract base class for loaders.
  32005. *
  32006. * @abstract
  32007. */
  32008. class Loader {
  32009. /**
  32010. * Constructs a new loader.
  32011. *
  32012. * @param {LoadingManager} [manager] - The loading manager.
  32013. */
  32014. constructor( manager ) {
  32015. /**
  32016. * The loading manager.
  32017. *
  32018. * @type {LoadingManager}
  32019. * @default DefaultLoadingManager
  32020. */
  32021. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32022. /**
  32023. * The crossOrigin string to implement CORS for loading the url from a
  32024. * different domain that allows CORS.
  32025. *
  32026. * @type {string}
  32027. * @default 'anonymous'
  32028. */
  32029. this.crossOrigin = 'anonymous';
  32030. /**
  32031. * Whether the XMLHttpRequest uses credentials.
  32032. *
  32033. * @type {boolean}
  32034. * @default false
  32035. */
  32036. this.withCredentials = false;
  32037. /**
  32038. * The base path from which the asset will be loaded.
  32039. *
  32040. * @type {string}
  32041. */
  32042. this.path = '';
  32043. /**
  32044. * The base path from which additional resources like textures will be loaded.
  32045. *
  32046. * @type {string}
  32047. */
  32048. this.resourcePath = '';
  32049. /**
  32050. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  32051. * used in HTTP request.
  32052. *
  32053. * @type {Object<string, any>}
  32054. */
  32055. this.requestHeader = {};
  32056. }
  32057. /**
  32058. * This method needs to be implemented by all concrete loaders. It holds the
  32059. * logic for loading assets from the backend.
  32060. *
  32061. * @abstract
  32062. * @param {string} url - The path/URL of the file to be loaded.
  32063. * @param {Function} onLoad - Executed when the loading process has been finished.
  32064. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32065. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32066. */
  32067. load( /* url, onLoad, onProgress, onError */ ) {}
  32068. /**
  32069. * A async version of {@link Loader#load}.
  32070. *
  32071. * @param {string} url - The path/URL of the file to be loaded.
  32072. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32073. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32074. */
  32075. loadAsync( url, onProgress ) {
  32076. const scope = this;
  32077. return new Promise( function ( resolve, reject ) {
  32078. scope.load( url, resolve, onProgress, reject );
  32079. } );
  32080. }
  32081. /**
  32082. * This method needs to be implemented by all concrete loaders. It holds the
  32083. * logic for parsing the asset into three.js entities.
  32084. *
  32085. * @abstract
  32086. * @param {any} data - The data to parse.
  32087. */
  32088. parse( /* data */ ) {}
  32089. /**
  32090. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32091. * from a different domain that allows CORS.
  32092. *
  32093. * @param {string} crossOrigin - The `crossOrigin` value.
  32094. * @return {Loader} A reference to this instance.
  32095. */
  32096. setCrossOrigin( crossOrigin ) {
  32097. this.crossOrigin = crossOrigin;
  32098. return this;
  32099. }
  32100. /**
  32101. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32102. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  32103. *
  32104. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32105. *
  32106. * @param {boolean} value - The `withCredentials` value.
  32107. * @return {Loader} A reference to this instance.
  32108. */
  32109. setWithCredentials( value ) {
  32110. this.withCredentials = value;
  32111. return this;
  32112. }
  32113. /**
  32114. * Sets the base path for the asset.
  32115. *
  32116. * @param {string} path - The base path.
  32117. * @return {Loader} A reference to this instance.
  32118. */
  32119. setPath( path ) {
  32120. this.path = path;
  32121. return this;
  32122. }
  32123. /**
  32124. * Sets the base path for dependent resources like textures.
  32125. *
  32126. * @param {string} resourcePath - The resource path.
  32127. * @return {Loader} A reference to this instance.
  32128. */
  32129. setResourcePath( resourcePath ) {
  32130. this.resourcePath = resourcePath;
  32131. return this;
  32132. }
  32133. /**
  32134. * Sets the given request header.
  32135. *
  32136. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  32137. * for configuring the HTTP request.
  32138. * @return {Loader} A reference to this instance.
  32139. */
  32140. setRequestHeader( requestHeader ) {
  32141. this.requestHeader = requestHeader;
  32142. return this;
  32143. }
  32144. /**
  32145. * This method can be implemented in loaders for aborting ongoing requests.
  32146. *
  32147. * @abstract
  32148. * @return {Loader} A reference to this instance.
  32149. */
  32150. abort() {
  32151. return this;
  32152. }
  32153. }
  32154. /**
  32155. * Callback for onProgress in loaders.
  32156. *
  32157. * @callback onProgressCallback
  32158. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32159. */
  32160. /**
  32161. * Callback for onError in loaders.
  32162. *
  32163. * @callback onErrorCallback
  32164. * @param {Error} error - The error which occurred during the loading process.
  32165. */
  32166. /**
  32167. * The default material name that is used by loaders
  32168. * when creating materials for loaded 3D objects.
  32169. *
  32170. * Note: Not all loaders might honor this setting.
  32171. *
  32172. * @static
  32173. * @type {string}
  32174. * @default '__DEFAULT'
  32175. */
  32176. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32177. const loading = {};
  32178. class HttpError extends Error {
  32179. constructor( message, response ) {
  32180. super( message );
  32181. this.response = response;
  32182. }
  32183. }
  32184. /**
  32185. * A low level class for loading resources with the Fetch API, used internally by
  32186. * most loaders. It can also be used directly to load any file type that does
  32187. * not have a loader.
  32188. *
  32189. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32190. * once to your application.
  32191. *
  32192. * ```js
  32193. * const loader = new THREE.FileLoader();
  32194. * const data = await loader.loadAsync( 'example.txt' );
  32195. * ```
  32196. *
  32197. * @augments Loader
  32198. */
  32199. class FileLoader extends Loader {
  32200. /**
  32201. * Constructs a new file loader.
  32202. *
  32203. * @param {LoadingManager} [manager] - The loading manager.
  32204. */
  32205. constructor( manager ) {
  32206. super( manager );
  32207. /**
  32208. * The expected mime type. Valid values can be found
  32209. * [here]{@link hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype}
  32210. *
  32211. * @type {string}
  32212. */
  32213. this.mimeType = '';
  32214. /**
  32215. * The expected response type.
  32216. *
  32217. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32218. * @default ''
  32219. */
  32220. this.responseType = '';
  32221. /**
  32222. * Used for aborting requests.
  32223. *
  32224. * @private
  32225. * @type {AbortController}
  32226. */
  32227. this._abortController = new AbortController();
  32228. }
  32229. /**
  32230. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32231. *
  32232. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32233. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32234. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32235. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32236. * @return {any|undefined} The cached resource if available.
  32237. */
  32238. load( url, onLoad, onProgress, onError ) {
  32239. if ( url === undefined ) url = '';
  32240. if ( this.path !== undefined ) url = this.path + url;
  32241. url = this.manager.resolveURL( url );
  32242. const cached = Cache.get( `file:${url}` );
  32243. if ( cached !== undefined ) {
  32244. this.manager.itemStart( url );
  32245. setTimeout( () => {
  32246. if ( onLoad ) onLoad( cached );
  32247. this.manager.itemEnd( url );
  32248. }, 0 );
  32249. return cached;
  32250. }
  32251. // Check if request is duplicate
  32252. if ( loading[ url ] !== undefined ) {
  32253. loading[ url ].push( {
  32254. onLoad: onLoad,
  32255. onProgress: onProgress,
  32256. onError: onError
  32257. } );
  32258. return;
  32259. }
  32260. // Initialise array for duplicate requests
  32261. loading[ url ] = [];
  32262. loading[ url ].push( {
  32263. onLoad: onLoad,
  32264. onProgress: onProgress,
  32265. onError: onError,
  32266. } );
  32267. // create request
  32268. const req = new Request( url, {
  32269. headers: new Headers( this.requestHeader ),
  32270. credentials: this.withCredentials ? 'include' : 'same-origin',
  32271. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32272. } );
  32273. // record states ( avoid data race )
  32274. const mimeType = this.mimeType;
  32275. const responseType = this.responseType;
  32276. // start the fetch
  32277. fetch( req )
  32278. .then( response => {
  32279. if ( response.status === 200 || response.status === 0 ) {
  32280. // Some browsers return HTTP Status 0 when using non-http protocol
  32281. // e.g. 'file://' or 'data://'. Handle as success.
  32282. if ( response.status === 0 ) {
  32283. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  32284. }
  32285. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32286. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32287. return response;
  32288. }
  32289. const callbacks = loading[ url ];
  32290. const reader = response.body.getReader();
  32291. // Nginx needs X-File-Size check
  32292. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32293. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32294. const total = contentLength ? parseInt( contentLength ) : 0;
  32295. const lengthComputable = total !== 0;
  32296. let loaded = 0;
  32297. // periodically read data into the new stream tracking while download progress
  32298. const stream = new ReadableStream( {
  32299. start( controller ) {
  32300. readData();
  32301. function readData() {
  32302. reader.read().then( ( { done, value } ) => {
  32303. if ( done ) {
  32304. controller.close();
  32305. } else {
  32306. loaded += value.byteLength;
  32307. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32308. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32309. const callback = callbacks[ i ];
  32310. if ( callback.onProgress ) callback.onProgress( event );
  32311. }
  32312. controller.enqueue( value );
  32313. readData();
  32314. }
  32315. }, ( e ) => {
  32316. controller.error( e );
  32317. } );
  32318. }
  32319. }
  32320. } );
  32321. return new Response( stream );
  32322. } else {
  32323. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32324. }
  32325. } )
  32326. .then( response => {
  32327. switch ( responseType ) {
  32328. case 'arraybuffer':
  32329. return response.arrayBuffer();
  32330. case 'blob':
  32331. return response.blob();
  32332. case 'document':
  32333. return response.text()
  32334. .then( text => {
  32335. const parser = new DOMParser();
  32336. return parser.parseFromString( text, mimeType );
  32337. } );
  32338. case 'json':
  32339. return response.json();
  32340. default:
  32341. if ( mimeType === '' ) {
  32342. return response.text();
  32343. } else {
  32344. // sniff encoding
  32345. const re = /charset="?([^;"\s]*)"?/i;
  32346. const exec = re.exec( mimeType );
  32347. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32348. const decoder = new TextDecoder( label );
  32349. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32350. }
  32351. }
  32352. } )
  32353. .then( data => {
  32354. // Add to cache only on HTTP success, so that we do not cache
  32355. // error response bodies as proper responses to requests.
  32356. Cache.add( `file:${url}`, data );
  32357. const callbacks = loading[ url ];
  32358. delete loading[ url ];
  32359. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32360. const callback = callbacks[ i ];
  32361. if ( callback.onLoad ) callback.onLoad( data );
  32362. }
  32363. } )
  32364. .catch( err => {
  32365. // Abort errors and other errors are handled the same
  32366. const callbacks = loading[ url ];
  32367. if ( callbacks === undefined ) {
  32368. // When onLoad was called and url was deleted in `loading`
  32369. this.manager.itemError( url );
  32370. throw err;
  32371. }
  32372. delete loading[ url ];
  32373. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32374. const callback = callbacks[ i ];
  32375. if ( callback.onError ) callback.onError( err );
  32376. }
  32377. this.manager.itemError( url );
  32378. } )
  32379. .finally( () => {
  32380. this.manager.itemEnd( url );
  32381. } );
  32382. this.manager.itemStart( url );
  32383. }
  32384. /**
  32385. * Sets the expected response type.
  32386. *
  32387. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32388. * @return {FileLoader} A reference to this file loader.
  32389. */
  32390. setResponseType( value ) {
  32391. this.responseType = value;
  32392. return this;
  32393. }
  32394. /**
  32395. * Sets the expected mime type of the loaded file.
  32396. *
  32397. * @param {string} value - The mime type.
  32398. * @return {FileLoader} A reference to this file loader.
  32399. */
  32400. setMimeType( value ) {
  32401. this.mimeType = value;
  32402. return this;
  32403. }
  32404. /**
  32405. * Aborts ongoing fetch requests.
  32406. *
  32407. * @return {FileLoader} A reference to this instance.
  32408. */
  32409. abort() {
  32410. this._abortController.abort();
  32411. this._abortController = new AbortController();
  32412. return this;
  32413. }
  32414. }
  32415. /**
  32416. * Class for loading animation clips in the JSON format. The files are internally
  32417. * loaded via {@link FileLoader}.
  32418. *
  32419. * ```js
  32420. * const loader = new THREE.AnimationLoader();
  32421. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32422. * ```
  32423. *
  32424. * @augments Loader
  32425. */
  32426. class AnimationLoader extends Loader {
  32427. /**
  32428. * Constructs a new animation loader.
  32429. *
  32430. * @param {LoadingManager} [manager] - The loading manager.
  32431. */
  32432. constructor( manager ) {
  32433. super( manager );
  32434. }
  32435. /**
  32436. * Starts loading from the given URL and pass the loaded animations as an array
  32437. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32438. *
  32439. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32440. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32441. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32442. * @param {onErrorCallback} onError - Executed when errors occur.
  32443. */
  32444. load( url, onLoad, onProgress, onError ) {
  32445. const scope = this;
  32446. const loader = new FileLoader( this.manager );
  32447. loader.setPath( this.path );
  32448. loader.setRequestHeader( this.requestHeader );
  32449. loader.setWithCredentials( this.withCredentials );
  32450. loader.load( url, function ( text ) {
  32451. try {
  32452. onLoad( scope.parse( JSON.parse( text ) ) );
  32453. } catch ( e ) {
  32454. if ( onError ) {
  32455. onError( e );
  32456. } else {
  32457. console.error( e );
  32458. }
  32459. scope.manager.itemError( url );
  32460. }
  32461. }, onProgress, onError );
  32462. }
  32463. /**
  32464. * Parses the given JSON object and returns an array of animation clips.
  32465. *
  32466. * @param {Object} json - The serialized animation clips.
  32467. * @return {Array<AnimationClip>} The parsed animation clips.
  32468. */
  32469. parse( json ) {
  32470. const animations = [];
  32471. for ( let i = 0; i < json.length; i ++ ) {
  32472. const clip = AnimationClip.parse( json[ i ] );
  32473. animations.push( clip );
  32474. }
  32475. return animations;
  32476. }
  32477. }
  32478. /**
  32479. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32480. * Textures are internally loaded via {@link FileLoader}.
  32481. *
  32482. * Derived classes have to implement the `parse()` method which holds the parsing
  32483. * for the respective format.
  32484. *
  32485. * @abstract
  32486. * @augments Loader
  32487. */
  32488. class CompressedTextureLoader extends Loader {
  32489. /**
  32490. * Constructs a new compressed texture loader.
  32491. *
  32492. * @param {LoadingManager} [manager] - The loading manager.
  32493. */
  32494. constructor( manager ) {
  32495. super( manager );
  32496. }
  32497. /**
  32498. * Starts loading from the given URL and passes the loaded compressed texture
  32499. * to the `onLoad()` callback. The method also returns a new texture object which can
  32500. * directly be used for material creation. If you do it this way, the texture
  32501. * may pop up in your scene once the respective loading process is finished.
  32502. *
  32503. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32504. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32505. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32506. * @param {onErrorCallback} onError - Executed when errors occur.
  32507. * @return {CompressedTexture} The compressed texture.
  32508. */
  32509. load( url, onLoad, onProgress, onError ) {
  32510. const scope = this;
  32511. const images = [];
  32512. const texture = new CompressedTexture();
  32513. const loader = new FileLoader( this.manager );
  32514. loader.setPath( this.path );
  32515. loader.setResponseType( 'arraybuffer' );
  32516. loader.setRequestHeader( this.requestHeader );
  32517. loader.setWithCredentials( scope.withCredentials );
  32518. let loaded = 0;
  32519. function loadTexture( i ) {
  32520. loader.load( url[ i ], function ( buffer ) {
  32521. const texDatas = scope.parse( buffer, true );
  32522. images[ i ] = {
  32523. width: texDatas.width,
  32524. height: texDatas.height,
  32525. format: texDatas.format,
  32526. mipmaps: texDatas.mipmaps
  32527. };
  32528. loaded += 1;
  32529. if ( loaded === 6 ) {
  32530. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32531. texture.image = images;
  32532. texture.format = texDatas.format;
  32533. texture.needsUpdate = true;
  32534. if ( onLoad ) onLoad( texture );
  32535. }
  32536. }, onProgress, onError );
  32537. }
  32538. if ( Array.isArray( url ) ) {
  32539. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32540. loadTexture( i );
  32541. }
  32542. } else {
  32543. // compressed cubemap texture stored in a single DDS file
  32544. loader.load( url, function ( buffer ) {
  32545. const texDatas = scope.parse( buffer, true );
  32546. if ( texDatas.isCubemap ) {
  32547. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32548. for ( let f = 0; f < faces; f ++ ) {
  32549. images[ f ] = { mipmaps: [] };
  32550. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32551. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32552. images[ f ].format = texDatas.format;
  32553. images[ f ].width = texDatas.width;
  32554. images[ f ].height = texDatas.height;
  32555. }
  32556. }
  32557. texture.image = images;
  32558. } else {
  32559. texture.image.width = texDatas.width;
  32560. texture.image.height = texDatas.height;
  32561. texture.mipmaps = texDatas.mipmaps;
  32562. }
  32563. if ( texDatas.mipmapCount === 1 ) {
  32564. texture.minFilter = LinearFilter;
  32565. }
  32566. texture.format = texDatas.format;
  32567. texture.needsUpdate = true;
  32568. if ( onLoad ) onLoad( texture );
  32569. }, onProgress, onError );
  32570. }
  32571. return texture;
  32572. }
  32573. }
  32574. const _loading = new WeakMap();
  32575. /**
  32576. * A loader for loading images. The class loads images with the HTML `Image` API.
  32577. *
  32578. * ```js
  32579. * const loader = new THREE.ImageLoader();
  32580. * const image = await loader.loadAsync( 'image.png' );
  32581. * ```
  32582. * Please note that `ImageLoader` has dropped support for progress
  32583. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32584. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}.
  32585. *
  32586. * @augments Loader
  32587. */
  32588. class ImageLoader extends Loader {
  32589. /**
  32590. * Constructs a new image loader.
  32591. *
  32592. * @param {LoadingManager} [manager] - The loading manager.
  32593. */
  32594. constructor( manager ) {
  32595. super( manager );
  32596. }
  32597. /**
  32598. * Starts loading from the given URL and passes the loaded image
  32599. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32600. * directly be used for texture creation. If you do it this way, the texture
  32601. * may pop up in your scene once the respective loading process is finished.
  32602. *
  32603. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32604. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32605. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32606. * @param {onErrorCallback} onError - Executed when errors occur.
  32607. * @return {Image} The image.
  32608. */
  32609. load( url, onLoad, onProgress, onError ) {
  32610. if ( this.path !== undefined ) url = this.path + url;
  32611. url = this.manager.resolveURL( url );
  32612. const scope = this;
  32613. const cached = Cache.get( `image:${url}` );
  32614. if ( cached !== undefined ) {
  32615. if ( cached.complete === true ) {
  32616. scope.manager.itemStart( url );
  32617. setTimeout( function () {
  32618. if ( onLoad ) onLoad( cached );
  32619. scope.manager.itemEnd( url );
  32620. }, 0 );
  32621. } else {
  32622. let arr = _loading.get( cached );
  32623. if ( arr === undefined ) {
  32624. arr = [];
  32625. _loading.set( cached, arr );
  32626. }
  32627. arr.push( { onLoad, onError } );
  32628. }
  32629. return cached;
  32630. }
  32631. const image = createElementNS( 'img' );
  32632. function onImageLoad() {
  32633. removeEventListeners();
  32634. if ( onLoad ) onLoad( this );
  32635. //
  32636. const callbacks = _loading.get( this ) || [];
  32637. for ( let i = 0; i < callbacks.length; i ++ ) {
  32638. const callback = callbacks[ i ];
  32639. if ( callback.onLoad ) callback.onLoad( this );
  32640. }
  32641. _loading.delete( this );
  32642. scope.manager.itemEnd( url );
  32643. }
  32644. function onImageError( event ) {
  32645. removeEventListeners();
  32646. if ( onError ) onError( event );
  32647. Cache.remove( `image:${url}` );
  32648. //
  32649. const callbacks = _loading.get( this ) || [];
  32650. for ( let i = 0; i < callbacks.length; i ++ ) {
  32651. const callback = callbacks[ i ];
  32652. if ( callback.onError ) callback.onError( event );
  32653. }
  32654. _loading.delete( this );
  32655. scope.manager.itemError( url );
  32656. scope.manager.itemEnd( url );
  32657. }
  32658. function removeEventListeners() {
  32659. image.removeEventListener( 'load', onImageLoad, false );
  32660. image.removeEventListener( 'error', onImageError, false );
  32661. }
  32662. image.addEventListener( 'load', onImageLoad, false );
  32663. image.addEventListener( 'error', onImageError, false );
  32664. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32665. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32666. }
  32667. Cache.add( `image:${url}`, image );
  32668. scope.manager.itemStart( url );
  32669. image.src = url;
  32670. return image;
  32671. }
  32672. }
  32673. /**
  32674. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32675. *
  32676. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32677. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32678. * like vertical and horizontal cross, column and row layouts are not supported.
  32679. *
  32680. * Note that, by convention, cube maps are specified in a coordinate system
  32681. * in which positive-x is to the right when looking up the positive-z axis --
  32682. * in other words, using a left-handed coordinate system. Since three.js uses
  32683. * a right-handed coordinate system, environment maps used in three.js will
  32684. * have pos-x and neg-x swapped.
  32685. *
  32686. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32687. * is set to `SRGBColorSpace` by default.
  32688. *
  32689. * ```js
  32690. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32691. * const cubeTexture = await loader.loadAsync( [
  32692. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32693. * ] );
  32694. * scene.background = cubeTexture;
  32695. * ```
  32696. *
  32697. * @augments Loader
  32698. */
  32699. class CubeTextureLoader extends Loader {
  32700. /**
  32701. * Constructs a new cube texture loader.
  32702. *
  32703. * @param {LoadingManager} [manager] - The loading manager.
  32704. */
  32705. constructor( manager ) {
  32706. super( manager );
  32707. }
  32708. /**
  32709. * Starts loading from the given URL and pass the fully loaded cube texture
  32710. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32711. * directly be used for material creation. If you do it this way, the cube texture
  32712. * may pop up in your scene once the respective loading process is finished.
  32713. *
  32714. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32715. * cube texture. The urls should be specified in the following order: pos-x,
  32716. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32717. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32718. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32719. * @param {onErrorCallback} onError - Executed when errors occur.
  32720. * @return {CubeTexture} The cube texture.
  32721. */
  32722. load( urls, onLoad, onProgress, onError ) {
  32723. const texture = new CubeTexture();
  32724. texture.colorSpace = SRGBColorSpace;
  32725. const loader = new ImageLoader( this.manager );
  32726. loader.setCrossOrigin( this.crossOrigin );
  32727. loader.setPath( this.path );
  32728. let loaded = 0;
  32729. function loadTexture( i ) {
  32730. loader.load( urls[ i ], function ( image ) {
  32731. texture.images[ i ] = image;
  32732. loaded ++;
  32733. if ( loaded === 6 ) {
  32734. texture.needsUpdate = true;
  32735. if ( onLoad ) onLoad( texture );
  32736. }
  32737. }, undefined, onError );
  32738. }
  32739. for ( let i = 0; i < urls.length; ++ i ) {
  32740. loadTexture( i );
  32741. }
  32742. return texture;
  32743. }
  32744. }
  32745. /**
  32746. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32747. * Textures are internally loaded via {@link FileLoader}.
  32748. *
  32749. * Derived classes have to implement the `parse()` method which holds the parsing
  32750. * for the respective format.
  32751. *
  32752. * @abstract
  32753. * @augments Loader
  32754. */
  32755. class DataTextureLoader extends Loader {
  32756. /**
  32757. * Constructs a new data texture loader.
  32758. *
  32759. * @param {LoadingManager} [manager] - The loading manager.
  32760. */
  32761. constructor( manager ) {
  32762. super( manager );
  32763. }
  32764. /**
  32765. * Starts loading from the given URL and passes the loaded data texture
  32766. * to the `onLoad()` callback. The method also returns a new texture object which can
  32767. * directly be used for material creation. If you do it this way, the texture
  32768. * may pop up in your scene once the respective loading process is finished.
  32769. *
  32770. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32771. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32772. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32773. * @param {onErrorCallback} onError - Executed when errors occur.
  32774. * @return {DataTexture} The data texture.
  32775. */
  32776. load( url, onLoad, onProgress, onError ) {
  32777. const scope = this;
  32778. const texture = new DataTexture();
  32779. const loader = new FileLoader( this.manager );
  32780. loader.setResponseType( 'arraybuffer' );
  32781. loader.setRequestHeader( this.requestHeader );
  32782. loader.setPath( this.path );
  32783. loader.setWithCredentials( scope.withCredentials );
  32784. loader.load( url, function ( buffer ) {
  32785. let texData;
  32786. try {
  32787. texData = scope.parse( buffer );
  32788. } catch ( error ) {
  32789. if ( onError !== undefined ) {
  32790. onError( error );
  32791. } else {
  32792. console.error( error );
  32793. return;
  32794. }
  32795. }
  32796. if ( texData.image !== undefined ) {
  32797. texture.image = texData.image;
  32798. } else if ( texData.data !== undefined ) {
  32799. texture.image.width = texData.width;
  32800. texture.image.height = texData.height;
  32801. texture.image.data = texData.data;
  32802. }
  32803. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32804. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32805. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32806. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32807. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32808. if ( texData.colorSpace !== undefined ) {
  32809. texture.colorSpace = texData.colorSpace;
  32810. }
  32811. if ( texData.flipY !== undefined ) {
  32812. texture.flipY = texData.flipY;
  32813. }
  32814. if ( texData.format !== undefined ) {
  32815. texture.format = texData.format;
  32816. }
  32817. if ( texData.type !== undefined ) {
  32818. texture.type = texData.type;
  32819. }
  32820. if ( texData.mipmaps !== undefined ) {
  32821. texture.mipmaps = texData.mipmaps;
  32822. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32823. }
  32824. if ( texData.mipmapCount === 1 ) {
  32825. texture.minFilter = LinearFilter;
  32826. }
  32827. if ( texData.generateMipmaps !== undefined ) {
  32828. texture.generateMipmaps = texData.generateMipmaps;
  32829. }
  32830. texture.needsUpdate = true;
  32831. if ( onLoad ) onLoad( texture, texData );
  32832. }, onProgress, onError );
  32833. return texture;
  32834. }
  32835. }
  32836. /**
  32837. * Class for loading textures. Images are internally
  32838. * loaded via {@link ImageLoader}.
  32839. *
  32840. * ```js
  32841. * const loader = new THREE.TextureLoader();
  32842. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32843. *
  32844. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32845. * ```
  32846. * Please note that `TextureLoader` has dropped support for progress
  32847. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32848. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}.
  32849. *
  32850. * @augments Loader
  32851. */
  32852. class TextureLoader extends Loader {
  32853. /**
  32854. * Constructs a new texture loader.
  32855. *
  32856. * @param {LoadingManager} [manager] - The loading manager.
  32857. */
  32858. constructor( manager ) {
  32859. super( manager );
  32860. }
  32861. /**
  32862. * Starts loading from the given URL and pass the fully loaded texture
  32863. * to the `onLoad()` callback. The method also returns a new texture object which can
  32864. * directly be used for material creation. If you do it this way, the texture
  32865. * may pop up in your scene once the respective loading process is finished.
  32866. *
  32867. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32868. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32869. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32870. * @param {onErrorCallback} onError - Executed when errors occur.
  32871. * @return {Texture} The texture.
  32872. */
  32873. load( url, onLoad, onProgress, onError ) {
  32874. const texture = new Texture();
  32875. const loader = new ImageLoader( this.manager );
  32876. loader.setCrossOrigin( this.crossOrigin );
  32877. loader.setPath( this.path );
  32878. loader.load( url, function ( image ) {
  32879. texture.image = image;
  32880. texture.needsUpdate = true;
  32881. if ( onLoad !== undefined ) {
  32882. onLoad( texture );
  32883. }
  32884. }, onProgress, onError );
  32885. return texture;
  32886. }
  32887. }
  32888. /**
  32889. * Abstract base class for lights - all other light types inherit the
  32890. * properties and methods described here.
  32891. *
  32892. * @abstract
  32893. * @augments Object3D
  32894. */
  32895. class Light extends Object3D {
  32896. /**
  32897. * Constructs a new light.
  32898. *
  32899. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32900. * @param {number} [intensity=1] - The light's strength/intensity.
  32901. */
  32902. constructor( color, intensity = 1 ) {
  32903. super();
  32904. /**
  32905. * This flag can be used for type testing.
  32906. *
  32907. * @type {boolean}
  32908. * @readonly
  32909. * @default true
  32910. */
  32911. this.isLight = true;
  32912. this.type = 'Light';
  32913. /**
  32914. * The light's color.
  32915. *
  32916. * @type {Color}
  32917. */
  32918. this.color = new Color( color );
  32919. /**
  32920. * The light's intensity.
  32921. *
  32922. * @type {number}
  32923. * @default 1
  32924. */
  32925. this.intensity = intensity;
  32926. }
  32927. /**
  32928. * Frees the GPU-related resources allocated by this instance. Call this
  32929. * method whenever this instance is no longer used in your app.
  32930. */
  32931. dispose() {
  32932. // Empty here in base class; some subclasses override.
  32933. }
  32934. copy( source, recursive ) {
  32935. super.copy( source, recursive );
  32936. this.color.copy( source.color );
  32937. this.intensity = source.intensity;
  32938. return this;
  32939. }
  32940. toJSON( meta ) {
  32941. const data = super.toJSON( meta );
  32942. data.object.color = this.color.getHex();
  32943. data.object.intensity = this.intensity;
  32944. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  32945. if ( this.distance !== undefined ) data.object.distance = this.distance;
  32946. if ( this.angle !== undefined ) data.object.angle = this.angle;
  32947. if ( this.decay !== undefined ) data.object.decay = this.decay;
  32948. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  32949. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  32950. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  32951. return data;
  32952. }
  32953. }
  32954. /**
  32955. * A light source positioned directly above the scene, with color fading from
  32956. * the sky color to the ground color.
  32957. *
  32958. * This light cannot be used to cast shadows.
  32959. *
  32960. * ```js
  32961. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32962. * scene.add( light );
  32963. * ```
  32964. *
  32965. * @augments Light
  32966. */
  32967. class HemisphereLight extends Light {
  32968. /**
  32969. * Constructs a new hemisphere light.
  32970. *
  32971. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32972. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32973. * @param {number} [intensity=1] - The light's strength/intensity.
  32974. */
  32975. constructor( skyColor, groundColor, intensity ) {
  32976. super( skyColor, intensity );
  32977. /**
  32978. * This flag can be used for type testing.
  32979. *
  32980. * @type {boolean}
  32981. * @readonly
  32982. * @default true
  32983. */
  32984. this.isHemisphereLight = true;
  32985. this.type = 'HemisphereLight';
  32986. this.position.copy( Object3D.DEFAULT_UP );
  32987. this.updateMatrix();
  32988. /**
  32989. * The light's ground color.
  32990. *
  32991. * @type {Color}
  32992. */
  32993. this.groundColor = new Color( groundColor );
  32994. }
  32995. copy( source, recursive ) {
  32996. super.copy( source, recursive );
  32997. this.groundColor.copy( source.groundColor );
  32998. return this;
  32999. }
  33000. }
  33001. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  33002. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  33003. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  33004. /**
  33005. * Abstract base class for light shadow classes. These classes
  33006. * represent the shadow configuration for different light types.
  33007. *
  33008. * @abstract
  33009. */
  33010. class LightShadow {
  33011. /**
  33012. * Constructs a new light shadow.
  33013. *
  33014. * @param {Camera} camera - The light's view of the world.
  33015. */
  33016. constructor( camera ) {
  33017. /**
  33018. * The light's view of the world.
  33019. *
  33020. * @type {Camera}
  33021. */
  33022. this.camera = camera;
  33023. /**
  33024. * The intensity of the shadow. The default is `1`.
  33025. * Valid values are in the range `[0, 1]`.
  33026. *
  33027. * @type {number}
  33028. * @default 1
  33029. */
  33030. this.intensity = 1;
  33031. /**
  33032. * Shadow map bias, how much to add or subtract from the normalized depth
  33033. * when deciding whether a surface is in shadow.
  33034. *
  33035. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33036. * may help reduce artifacts in shadows.
  33037. *
  33038. * @type {number}
  33039. * @default 0
  33040. */
  33041. this.bias = 0;
  33042. /**
  33043. * Defines how much the position used to query the shadow map is offset along
  33044. * the object normal. The default is `0`. Increasing this value can be used to
  33045. * reduce shadow acne especially in large scenes where light shines onto
  33046. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33047. *
  33048. * @type {number}
  33049. * @default 0
  33050. */
  33051. this.normalBias = 0;
  33052. /**
  33053. * Setting this to values greater than 1 will blur the edges of the shadow.
  33054. * High values will cause unwanted banding effects in the shadows - a greater
  33055. * map size will allow for a higher value to be used here before these effects
  33056. * become visible.
  33057. *
  33058. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  33059. * and it is recommended to increase softness by decreasing the shadow map size instead.
  33060. *
  33061. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33062. *
  33063. * @type {number}
  33064. * @default 1
  33065. */
  33066. this.radius = 1;
  33067. /**
  33068. * The amount of samples to use when blurring a VSM shadow map.
  33069. *
  33070. * @type {number}
  33071. * @default 8
  33072. */
  33073. this.blurSamples = 8;
  33074. /**
  33075. * Defines the width and height of the shadow map. Higher values give better quality
  33076. * shadows at the cost of computation time. Values must be powers of two.
  33077. *
  33078. * @type {Vector2}
  33079. * @default (512,512)
  33080. */
  33081. this.mapSize = new Vector2( 512, 512 );
  33082. /**
  33083. * The type of shadow texture. The default is `UnsignedByteType`.
  33084. *
  33085. * @type {number}
  33086. * @default UnsignedByteType
  33087. */
  33088. this.mapType = UnsignedByteType;
  33089. /**
  33090. * The depth map generated using the internal camera; a location beyond a
  33091. * pixel's depth is in shadow. Computed internally during rendering.
  33092. *
  33093. * @type {?RenderTarget}
  33094. * @default null
  33095. */
  33096. this.map = null;
  33097. /**
  33098. * The distribution map generated using the internal camera; an occlusion is
  33099. * calculated based on the distribution of depths. Computed internally during
  33100. * rendering.
  33101. *
  33102. * @type {?RenderTarget}
  33103. * @default null
  33104. */
  33105. this.mapPass = null;
  33106. /**
  33107. * Model to shadow camera space, to compute location and depth in shadow map.
  33108. * This is computed internally during rendering.
  33109. *
  33110. * @type {Matrix4}
  33111. */
  33112. this.matrix = new Matrix4();
  33113. /**
  33114. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33115. * lighting / shadows, you may set this to `false`.
  33116. *
  33117. * @type {boolean}
  33118. * @default true
  33119. */
  33120. this.autoUpdate = true;
  33121. /**
  33122. * When set to `true`, shadow maps will be updated in the next `render` call.
  33123. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33124. * set this property to `true` and then make a render call to update the light's shadow.
  33125. *
  33126. * @type {boolean}
  33127. * @default false
  33128. */
  33129. this.needsUpdate = false;
  33130. this._frustum = new Frustum();
  33131. this._frameExtents = new Vector2( 1, 1 );
  33132. this._viewportCount = 1;
  33133. this._viewports = [
  33134. new Vector4( 0, 0, 1, 1 )
  33135. ];
  33136. }
  33137. /**
  33138. * Used internally by the renderer to get the number of viewports that need
  33139. * to be rendered for this shadow.
  33140. *
  33141. * @return {number} The viewport count.
  33142. */
  33143. getViewportCount() {
  33144. return this._viewportCount;
  33145. }
  33146. /**
  33147. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33148. *
  33149. * @return {Frustum} The shadow camera frustum.
  33150. */
  33151. getFrustum() {
  33152. return this._frustum;
  33153. }
  33154. /**
  33155. * Update the matrices for the camera and shadow, used internally by the renderer.
  33156. *
  33157. * @param {Light} light - The light for which the shadow is being rendered.
  33158. */
  33159. updateMatrices( light ) {
  33160. const shadowCamera = this.camera;
  33161. const shadowMatrix = this.matrix;
  33162. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33163. shadowCamera.position.copy( _lightPositionWorld$1 );
  33164. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33165. shadowCamera.lookAt( _lookTarget$1 );
  33166. shadowCamera.updateMatrixWorld();
  33167. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33168. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33169. if ( shadowCamera.reversedDepth ) {
  33170. shadowMatrix.set(
  33171. 0.5, 0.0, 0.0, 0.5,
  33172. 0.0, 0.5, 0.0, 0.5,
  33173. 0.0, 0.0, 1.0, 0.0,
  33174. 0.0, 0.0, 0.0, 1.0
  33175. );
  33176. } else {
  33177. shadowMatrix.set(
  33178. 0.5, 0.0, 0.0, 0.5,
  33179. 0.0, 0.5, 0.0, 0.5,
  33180. 0.0, 0.0, 0.5, 0.5,
  33181. 0.0, 0.0, 0.0, 1.0
  33182. );
  33183. }
  33184. shadowMatrix.multiply( _projScreenMatrix$1 );
  33185. }
  33186. /**
  33187. * Returns a viewport definition for the given viewport index.
  33188. *
  33189. * @param {number} viewportIndex - The viewport index.
  33190. * @return {Vector4} The viewport.
  33191. */
  33192. getViewport( viewportIndex ) {
  33193. return this._viewports[ viewportIndex ];
  33194. }
  33195. /**
  33196. * Returns the frame extends.
  33197. *
  33198. * @return {Vector2} The frame extends.
  33199. */
  33200. getFrameExtents() {
  33201. return this._frameExtents;
  33202. }
  33203. /**
  33204. * Frees the GPU-related resources allocated by this instance. Call this
  33205. * method whenever this instance is no longer used in your app.
  33206. */
  33207. dispose() {
  33208. if ( this.map ) {
  33209. this.map.dispose();
  33210. }
  33211. if ( this.mapPass ) {
  33212. this.mapPass.dispose();
  33213. }
  33214. }
  33215. /**
  33216. * Copies the values of the given light shadow instance to this instance.
  33217. *
  33218. * @param {LightShadow} source - The light shadow to copy.
  33219. * @return {LightShadow} A reference to this light shadow instance.
  33220. */
  33221. copy( source ) {
  33222. this.camera = source.camera.clone();
  33223. this.intensity = source.intensity;
  33224. this.bias = source.bias;
  33225. this.radius = source.radius;
  33226. this.autoUpdate = source.autoUpdate;
  33227. this.needsUpdate = source.needsUpdate;
  33228. this.normalBias = source.normalBias;
  33229. this.blurSamples = source.blurSamples;
  33230. this.mapSize.copy( source.mapSize );
  33231. return this;
  33232. }
  33233. /**
  33234. * Returns a new light shadow instance with copied values from this instance.
  33235. *
  33236. * @return {LightShadow} A clone of this instance.
  33237. */
  33238. clone() {
  33239. return new this.constructor().copy( this );
  33240. }
  33241. /**
  33242. * Serializes the light shadow into JSON.
  33243. *
  33244. * @return {Object} A JSON object representing the serialized light shadow.
  33245. * @see {@link ObjectLoader#parse}
  33246. */
  33247. toJSON() {
  33248. const object = {};
  33249. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33250. if ( this.bias !== 0 ) object.bias = this.bias;
  33251. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33252. if ( this.radius !== 1 ) object.radius = this.radius;
  33253. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33254. object.camera = this.camera.toJSON( false ).object;
  33255. delete object.camera.matrix;
  33256. return object;
  33257. }
  33258. }
  33259. /**
  33260. * Represents the shadow configuration of directional lights.
  33261. *
  33262. * @augments LightShadow
  33263. */
  33264. class SpotLightShadow extends LightShadow {
  33265. /**
  33266. * Constructs a new spot light shadow.
  33267. */
  33268. constructor() {
  33269. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33270. /**
  33271. * This flag can be used for type testing.
  33272. *
  33273. * @type {boolean}
  33274. * @readonly
  33275. * @default true
  33276. */
  33277. this.isSpotLightShadow = true;
  33278. /**
  33279. * Used to focus the shadow camera. The camera's field of view is set as a
  33280. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33281. *
  33282. * @type {number}
  33283. * @default 1
  33284. */
  33285. this.focus = 1;
  33286. /**
  33287. * Texture aspect ratio.
  33288. *
  33289. * @type {number}
  33290. * @default 1
  33291. */
  33292. this.aspect = 1;
  33293. }
  33294. updateMatrices( light ) {
  33295. const camera = this.camera;
  33296. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33297. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33298. const far = light.distance || camera.far;
  33299. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33300. camera.fov = fov;
  33301. camera.aspect = aspect;
  33302. camera.far = far;
  33303. camera.updateProjectionMatrix();
  33304. }
  33305. super.updateMatrices( light );
  33306. }
  33307. copy( source ) {
  33308. super.copy( source );
  33309. this.focus = source.focus;
  33310. return this;
  33311. }
  33312. }
  33313. /**
  33314. * This light gets emitted from a single point in one direction, along a cone
  33315. * that increases in size the further from the light it gets.
  33316. *
  33317. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33318. *
  33319. * ```js
  33320. * // white spotlight shining from the side, modulated by a texture
  33321. * const spotLight = new THREE.SpotLight( 0xffffff );
  33322. * spotLight.position.set( 100, 1000, 100 );
  33323. * spotLight.map = new THREE.TextureLoader().load( url );
  33324. *
  33325. * spotLight.castShadow = true;
  33326. * spotLight.shadow.mapSize.width = 1024;
  33327. * spotLight.shadow.mapSize.height = 1024;
  33328. * spotLight.shadow.camera.near = 500;
  33329. * spotLight.shadow.camera.far = 4000;
  33330. * spotLight.shadow.camera.fov = 30;s
  33331. * ```
  33332. *
  33333. * @augments Light
  33334. */
  33335. class SpotLight extends Light {
  33336. /**
  33337. * Constructs a new spot light.
  33338. *
  33339. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33340. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33341. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33342. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33343. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33344. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33345. */
  33346. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33347. super( color, intensity );
  33348. /**
  33349. * This flag can be used for type testing.
  33350. *
  33351. * @type {boolean}
  33352. * @readonly
  33353. * @default true
  33354. */
  33355. this.isSpotLight = true;
  33356. this.type = 'SpotLight';
  33357. this.position.copy( Object3D.DEFAULT_UP );
  33358. this.updateMatrix();
  33359. /**
  33360. * The spot light points from its position to the
  33361. * target's position.
  33362. *
  33363. * For the target's position to be changed to anything other
  33364. * than the default, it must be added to the scene.
  33365. *
  33366. * It is also possible to set the target to be another 3D object
  33367. * in the scene. The light will now track the target object.
  33368. *
  33369. * @type {Object3D}
  33370. */
  33371. this.target = new Object3D();
  33372. /**
  33373. * Maximum range of the light. `0` means no limit.
  33374. *
  33375. * @type {number}
  33376. * @default 0
  33377. */
  33378. this.distance = distance;
  33379. /**
  33380. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33381. *
  33382. * @type {number}
  33383. * @default Math.PI/3
  33384. */
  33385. this.angle = angle;
  33386. /**
  33387. * Percent of the spotlight cone that is attenuated due to penumbra.
  33388. * Value range is `[0,1]`.
  33389. *
  33390. * @type {number}
  33391. * @default 0
  33392. */
  33393. this.penumbra = penumbra;
  33394. /**
  33395. * The amount the light dims along the distance of the light. In context of
  33396. * physically-correct rendering the default value should not be changed.
  33397. *
  33398. * @type {number}
  33399. * @default 2
  33400. */
  33401. this.decay = decay;
  33402. /**
  33403. * A texture used to modulate the color of the light. The spot light
  33404. * color is mixed with the RGB value of this texture, with a ratio
  33405. * corresponding to its alpha value. The cookie-like masking effect is
  33406. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33407. *
  33408. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33409. *
  33410. * @type {?Texture}
  33411. * @default null
  33412. */
  33413. this.map = null;
  33414. /**
  33415. * This property holds the light's shadow configuration.
  33416. *
  33417. * @type {SpotLightShadow}
  33418. */
  33419. this.shadow = new SpotLightShadow();
  33420. }
  33421. /**
  33422. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33423. * Changing the power will also change the light's intensity.
  33424. *
  33425. * @type {number}
  33426. */
  33427. get power() {
  33428. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33429. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33430. return this.intensity * Math.PI;
  33431. }
  33432. set power( power ) {
  33433. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33434. this.intensity = power / Math.PI;
  33435. }
  33436. dispose() {
  33437. this.shadow.dispose();
  33438. }
  33439. copy( source, recursive ) {
  33440. super.copy( source, recursive );
  33441. this.distance = source.distance;
  33442. this.angle = source.angle;
  33443. this.penumbra = source.penumbra;
  33444. this.decay = source.decay;
  33445. this.target = source.target.clone();
  33446. this.shadow = source.shadow.clone();
  33447. return this;
  33448. }
  33449. }
  33450. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33451. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33452. const _lookTarget = /*@__PURE__*/ new Vector3();
  33453. /**
  33454. * Represents the shadow configuration of point lights.
  33455. *
  33456. * @augments LightShadow
  33457. */
  33458. class PointLightShadow extends LightShadow {
  33459. /**
  33460. * Constructs a new point light shadow.
  33461. */
  33462. constructor() {
  33463. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33464. /**
  33465. * This flag can be used for type testing.
  33466. *
  33467. * @type {boolean}
  33468. * @readonly
  33469. * @default true
  33470. */
  33471. this.isPointLightShadow = true;
  33472. this._frameExtents = new Vector2( 4, 2 );
  33473. this._viewportCount = 6;
  33474. this._viewports = [
  33475. // These viewports map a cube-map onto a 2D texture with the
  33476. // following orientation:
  33477. //
  33478. // xzXZ
  33479. // y Y
  33480. //
  33481. // X - Positive x direction
  33482. // x - Negative x direction
  33483. // Y - Positive y direction
  33484. // y - Negative y direction
  33485. // Z - Positive z direction
  33486. // z - Negative z direction
  33487. // positive X
  33488. new Vector4( 2, 1, 1, 1 ),
  33489. // negative X
  33490. new Vector4( 0, 1, 1, 1 ),
  33491. // positive Z
  33492. new Vector4( 3, 1, 1, 1 ),
  33493. // negative Z
  33494. new Vector4( 1, 1, 1, 1 ),
  33495. // positive Y
  33496. new Vector4( 3, 0, 1, 1 ),
  33497. // negative Y
  33498. new Vector4( 1, 0, 1, 1 )
  33499. ];
  33500. this._cubeDirections = [
  33501. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  33502. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  33503. ];
  33504. this._cubeUps = [
  33505. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  33506. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  33507. ];
  33508. }
  33509. /**
  33510. * Update the matrices for the camera and shadow, used internally by the renderer.
  33511. *
  33512. * @param {Light} light - The light for which the shadow is being rendered.
  33513. * @param {number} [viewportIndex=0] - The viewport index.
  33514. */
  33515. updateMatrices( light, viewportIndex = 0 ) {
  33516. const camera = this.camera;
  33517. const shadowMatrix = this.matrix;
  33518. const far = light.distance || camera.far;
  33519. if ( far !== camera.far ) {
  33520. camera.far = far;
  33521. camera.updateProjectionMatrix();
  33522. }
  33523. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33524. camera.position.copy( _lightPositionWorld );
  33525. _lookTarget.copy( camera.position );
  33526. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  33527. camera.up.copy( this._cubeUps[ viewportIndex ] );
  33528. camera.lookAt( _lookTarget );
  33529. camera.updateMatrixWorld();
  33530. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  33531. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33532. this._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  33533. }
  33534. }
  33535. /**
  33536. * A light that gets emitted from a single point in all directions. A common
  33537. * use case for this is to replicate the light emitted from a bare
  33538. * lightbulb.
  33539. *
  33540. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33541. *
  33542. * ```js
  33543. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33544. * light.position.set( 50, 50, 50 );
  33545. * scene.add( light );
  33546. * ```
  33547. *
  33548. * @augments Light
  33549. */
  33550. class PointLight extends Light {
  33551. /**
  33552. * Constructs a new point light.
  33553. *
  33554. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33555. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33556. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33557. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33558. */
  33559. constructor( color, intensity, distance = 0, decay = 2 ) {
  33560. super( color, intensity );
  33561. /**
  33562. * This flag can be used for type testing.
  33563. *
  33564. * @type {boolean}
  33565. * @readonly
  33566. * @default true
  33567. */
  33568. this.isPointLight = true;
  33569. this.type = 'PointLight';
  33570. /**
  33571. * When distance is zero, light will attenuate according to inverse-square
  33572. * law to infinite distance. When distance is non-zero, light will attenuate
  33573. * according to inverse-square law until near the distance cutoff, where it
  33574. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33575. * physically correct.
  33576. *
  33577. * @type {number}
  33578. * @default 0
  33579. */
  33580. this.distance = distance;
  33581. /**
  33582. * The amount the light dims along the distance of the light. In context of
  33583. * physically-correct rendering the default value should not be changed.
  33584. *
  33585. * @type {number}
  33586. * @default 2
  33587. */
  33588. this.decay = decay;
  33589. /**
  33590. * This property holds the light's shadow configuration.
  33591. *
  33592. * @type {PointLightShadow}
  33593. */
  33594. this.shadow = new PointLightShadow();
  33595. }
  33596. /**
  33597. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33598. * Changing the power will also change the light's intensity.
  33599. *
  33600. * @type {number}
  33601. */
  33602. get power() {
  33603. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33604. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33605. return this.intensity * 4 * Math.PI;
  33606. }
  33607. set power( power ) {
  33608. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33609. this.intensity = power / ( 4 * Math.PI );
  33610. }
  33611. dispose() {
  33612. this.shadow.dispose();
  33613. }
  33614. copy( source, recursive ) {
  33615. super.copy( source, recursive );
  33616. this.distance = source.distance;
  33617. this.decay = source.decay;
  33618. this.shadow = source.shadow.clone();
  33619. return this;
  33620. }
  33621. }
  33622. /**
  33623. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  33624. *
  33625. * In this projection mode, an object's size in the rendered image stays
  33626. * constant regardless of its distance from the camera. This can be useful
  33627. * for rendering 2D scenes and UI elements, amongst other things.
  33628. *
  33629. * ```js
  33630. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33631. * scene.add( camera );
  33632. * ```
  33633. *
  33634. * @augments Camera
  33635. */
  33636. class OrthographicCamera extends Camera {
  33637. /**
  33638. * Constructs a new orthographic camera.
  33639. *
  33640. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33641. * @param {number} [right=1] - The right plane of the camera's frustum.
  33642. * @param {number} [top=1] - The top plane of the camera's frustum.
  33643. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33644. * @param {number} [near=0.1] - The camera's near plane.
  33645. * @param {number} [far=2000] - The camera's far plane.
  33646. */
  33647. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33648. super();
  33649. /**
  33650. * This flag can be used for type testing.
  33651. *
  33652. * @type {boolean}
  33653. * @readonly
  33654. * @default true
  33655. */
  33656. this.isOrthographicCamera = true;
  33657. this.type = 'OrthographicCamera';
  33658. /**
  33659. * The zoom factor of the camera.
  33660. *
  33661. * @type {number}
  33662. * @default 1
  33663. */
  33664. this.zoom = 1;
  33665. /**
  33666. * Represents the frustum window specification. This property should not be edited
  33667. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33668. *
  33669. * @type {?Object}
  33670. * @default null
  33671. */
  33672. this.view = null;
  33673. /**
  33674. * The left plane of the camera's frustum.
  33675. *
  33676. * @type {number}
  33677. * @default -1
  33678. */
  33679. this.left = left;
  33680. /**
  33681. * The right plane of the camera's frustum.
  33682. *
  33683. * @type {number}
  33684. * @default 1
  33685. */
  33686. this.right = right;
  33687. /**
  33688. * The top plane of the camera's frustum.
  33689. *
  33690. * @type {number}
  33691. * @default 1
  33692. */
  33693. this.top = top;
  33694. /**
  33695. * The bottom plane of the camera's frustum.
  33696. *
  33697. * @type {number}
  33698. * @default -1
  33699. */
  33700. this.bottom = bottom;
  33701. /**
  33702. * The camera's near plane. The valid range is greater than `0`
  33703. * and less than the current value of {@link OrthographicCamera#far}.
  33704. *
  33705. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33706. * valid value for an orthographic camera's near plane.
  33707. *
  33708. * @type {number}
  33709. * @default 0.1
  33710. */
  33711. this.near = near;
  33712. /**
  33713. * The camera's far plane. Must be greater than the
  33714. * current value of {@link OrthographicCamera#near}.
  33715. *
  33716. * @type {number}
  33717. * @default 2000
  33718. */
  33719. this.far = far;
  33720. this.updateProjectionMatrix();
  33721. }
  33722. copy( source, recursive ) {
  33723. super.copy( source, recursive );
  33724. this.left = source.left;
  33725. this.right = source.right;
  33726. this.top = source.top;
  33727. this.bottom = source.bottom;
  33728. this.near = source.near;
  33729. this.far = source.far;
  33730. this.zoom = source.zoom;
  33731. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33732. return this;
  33733. }
  33734. /**
  33735. * Sets an offset in a larger frustum. This is useful for multi-window or
  33736. * multi-monitor/multi-machine setups.
  33737. *
  33738. * @param {number} fullWidth - The full width of multiview setup.
  33739. * @param {number} fullHeight - The full height of multiview setup.
  33740. * @param {number} x - The horizontal offset of the subcamera.
  33741. * @param {number} y - The vertical offset of the subcamera.
  33742. * @param {number} width - The width of subcamera.
  33743. * @param {number} height - The height of subcamera.
  33744. * @see {@link PerspectiveCamera#setViewOffset}
  33745. */
  33746. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33747. if ( this.view === null ) {
  33748. this.view = {
  33749. enabled: true,
  33750. fullWidth: 1,
  33751. fullHeight: 1,
  33752. offsetX: 0,
  33753. offsetY: 0,
  33754. width: 1,
  33755. height: 1
  33756. };
  33757. }
  33758. this.view.enabled = true;
  33759. this.view.fullWidth = fullWidth;
  33760. this.view.fullHeight = fullHeight;
  33761. this.view.offsetX = x;
  33762. this.view.offsetY = y;
  33763. this.view.width = width;
  33764. this.view.height = height;
  33765. this.updateProjectionMatrix();
  33766. }
  33767. /**
  33768. * Removes the view offset from the projection matrix.
  33769. */
  33770. clearViewOffset() {
  33771. if ( this.view !== null ) {
  33772. this.view.enabled = false;
  33773. }
  33774. this.updateProjectionMatrix();
  33775. }
  33776. /**
  33777. * Updates the camera's projection matrix. Must be called after any change of
  33778. * camera properties.
  33779. */
  33780. updateProjectionMatrix() {
  33781. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33782. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33783. const cx = ( this.right + this.left ) / 2;
  33784. const cy = ( this.top + this.bottom ) / 2;
  33785. let left = cx - dx;
  33786. let right = cx + dx;
  33787. let top = cy + dy;
  33788. let bottom = cy - dy;
  33789. if ( this.view !== null && this.view.enabled ) {
  33790. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33791. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33792. left += scaleW * this.view.offsetX;
  33793. right = left + scaleW * this.view.width;
  33794. top -= scaleH * this.view.offsetY;
  33795. bottom = top - scaleH * this.view.height;
  33796. }
  33797. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  33798. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33799. }
  33800. toJSON( meta ) {
  33801. const data = super.toJSON( meta );
  33802. data.object.zoom = this.zoom;
  33803. data.object.left = this.left;
  33804. data.object.right = this.right;
  33805. data.object.top = this.top;
  33806. data.object.bottom = this.bottom;
  33807. data.object.near = this.near;
  33808. data.object.far = this.far;
  33809. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33810. return data;
  33811. }
  33812. }
  33813. /**
  33814. * Represents the shadow configuration of directional lights.
  33815. *
  33816. * @augments LightShadow
  33817. */
  33818. class DirectionalLightShadow extends LightShadow {
  33819. /**
  33820. * Constructs a new directional light shadow.
  33821. */
  33822. constructor() {
  33823. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  33824. /**
  33825. * This flag can be used for type testing.
  33826. *
  33827. * @type {boolean}
  33828. * @readonly
  33829. * @default true
  33830. */
  33831. this.isDirectionalLightShadow = true;
  33832. }
  33833. }
  33834. /**
  33835. * A light that gets emitted in a specific direction. This light will behave
  33836. * as though it is infinitely far away and the rays produced from it are all
  33837. * parallel. The common use case for this is to simulate daylight; the sun is
  33838. * far enough away that its position can be considered to be infinite, and
  33839. * all light rays coming from it are parallel.
  33840. *
  33841. * A common point of confusion for directional lights is that setting the
  33842. * rotation has no effect. This is because three.js's DirectionalLight is the
  33843. * equivalent to what is often called a 'Target Direct Light' in other
  33844. * applications.
  33845. *
  33846. * This means that its direction is calculated as pointing from the light's
  33847. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  33848. * (as opposed to a 'Free Direct Light' that just has a rotation
  33849. * component).
  33850. *
  33851. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  33852. *
  33853. * ```js
  33854. * // White directional light at half intensity shining from the top.
  33855. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  33856. * scene.add( directionalLight );
  33857. * ```
  33858. *
  33859. * @augments Light
  33860. */
  33861. class DirectionalLight extends Light {
  33862. /**
  33863. * Constructs a new directional light.
  33864. *
  33865. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33866. * @param {number} [intensity=1] - The light's strength/intensity.
  33867. */
  33868. constructor( color, intensity ) {
  33869. super( color, intensity );
  33870. /**
  33871. * This flag can be used for type testing.
  33872. *
  33873. * @type {boolean}
  33874. * @readonly
  33875. * @default true
  33876. */
  33877. this.isDirectionalLight = true;
  33878. this.type = 'DirectionalLight';
  33879. this.position.copy( Object3D.DEFAULT_UP );
  33880. this.updateMatrix();
  33881. /**
  33882. * The directional light points from its position to the
  33883. * target's position.
  33884. *
  33885. * For the target's position to be changed to anything other
  33886. * than the default, it must be added to the scene.
  33887. *
  33888. * It is also possible to set the target to be another 3D object
  33889. * in the scene. The light will now track the target object.
  33890. *
  33891. * @type {Object3D}
  33892. */
  33893. this.target = new Object3D();
  33894. /**
  33895. * This property holds the light's shadow configuration.
  33896. *
  33897. * @type {DirectionalLightShadow}
  33898. */
  33899. this.shadow = new DirectionalLightShadow();
  33900. }
  33901. dispose() {
  33902. this.shadow.dispose();
  33903. }
  33904. copy( source ) {
  33905. super.copy( source );
  33906. this.target = source.target.clone();
  33907. this.shadow = source.shadow.clone();
  33908. return this;
  33909. }
  33910. }
  33911. /**
  33912. * This light globally illuminates all objects in the scene equally.
  33913. *
  33914. * It cannot be used to cast shadows as it does not have a direction.
  33915. *
  33916. * ```js
  33917. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  33918. * scene.add( light );
  33919. * ```
  33920. *
  33921. * @augments Light
  33922. */
  33923. class AmbientLight extends Light {
  33924. /**
  33925. * Constructs a new ambient light.
  33926. *
  33927. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33928. * @param {number} [intensity=1] - The light's strength/intensity.
  33929. */
  33930. constructor( color, intensity ) {
  33931. super( color, intensity );
  33932. /**
  33933. * This flag can be used for type testing.
  33934. *
  33935. * @type {boolean}
  33936. * @readonly
  33937. * @default true
  33938. */
  33939. this.isAmbientLight = true;
  33940. this.type = 'AmbientLight';
  33941. }
  33942. }
  33943. /**
  33944. * This class emits light uniformly across the face a rectangular plane.
  33945. * This light type can be used to simulate light sources such as bright
  33946. * windows or strip lighting.
  33947. *
  33948. * Important Notes:
  33949. *
  33950. * - There is no shadow support.
  33951. * - Only PBR materials are supported.
  33952. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  33953. * into your app and init the uniforms/textures.
  33954. *
  33955. * ```js
  33956. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  33957. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  33958. *
  33959. * const intensity = 1; const width = 10; const height = 10;
  33960. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  33961. * rectLight.position.set( 5, 5, 0 );
  33962. * rectLight.lookAt( 0, 0, 0 );
  33963. * scene.add( rectLight )
  33964. * ```
  33965. *
  33966. * @augments Light
  33967. */
  33968. class RectAreaLight extends Light {
  33969. /**
  33970. * Constructs a new area light.
  33971. *
  33972. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33973. * @param {number} [intensity=1] - The light's strength/intensity.
  33974. * @param {number} [width=10] - The width of the light.
  33975. * @param {number} [height=10] - The height of the light.
  33976. */
  33977. constructor( color, intensity, width = 10, height = 10 ) {
  33978. super( color, intensity );
  33979. /**
  33980. * This flag can be used for type testing.
  33981. *
  33982. * @type {boolean}
  33983. * @readonly
  33984. * @default true
  33985. */
  33986. this.isRectAreaLight = true;
  33987. this.type = 'RectAreaLight';
  33988. /**
  33989. * The width of the light.
  33990. *
  33991. * @type {number}
  33992. * @default 10
  33993. */
  33994. this.width = width;
  33995. /**
  33996. * The height of the light.
  33997. *
  33998. * @type {number}
  33999. * @default 10
  34000. */
  34001. this.height = height;
  34002. }
  34003. /**
  34004. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34005. * Changing the power will also change the light's intensity.
  34006. *
  34007. * @type {number}
  34008. */
  34009. get power() {
  34010. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34011. return this.intensity * this.width * this.height * Math.PI;
  34012. }
  34013. set power( power ) {
  34014. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34015. this.intensity = power / ( this.width * this.height * Math.PI );
  34016. }
  34017. copy( source ) {
  34018. super.copy( source );
  34019. this.width = source.width;
  34020. this.height = source.height;
  34021. return this;
  34022. }
  34023. toJSON( meta ) {
  34024. const data = super.toJSON( meta );
  34025. data.object.width = this.width;
  34026. data.object.height = this.height;
  34027. return data;
  34028. }
  34029. }
  34030. /**
  34031. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34032. * to encode lighting information.
  34033. *
  34034. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34035. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34036. */
  34037. class SphericalHarmonics3 {
  34038. /**
  34039. * Constructs a new spherical harmonics.
  34040. */
  34041. constructor() {
  34042. /**
  34043. * This flag can be used for type testing.
  34044. *
  34045. * @type {boolean}
  34046. * @readonly
  34047. * @default true
  34048. */
  34049. this.isSphericalHarmonics3 = true;
  34050. /**
  34051. * An array holding the (9) SH coefficients.
  34052. *
  34053. * @type {Array<Vector3>}
  34054. */
  34055. this.coefficients = [];
  34056. for ( let i = 0; i < 9; i ++ ) {
  34057. this.coefficients.push( new Vector3() );
  34058. }
  34059. }
  34060. /**
  34061. * Sets the given SH coefficients to this instance by copying
  34062. * the values.
  34063. *
  34064. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34065. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34066. */
  34067. set( coefficients ) {
  34068. for ( let i = 0; i < 9; i ++ ) {
  34069. this.coefficients[ i ].copy( coefficients[ i ] );
  34070. }
  34071. return this;
  34072. }
  34073. /**
  34074. * Sets all SH coefficients to `0`.
  34075. *
  34076. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34077. */
  34078. zero() {
  34079. for ( let i = 0; i < 9; i ++ ) {
  34080. this.coefficients[ i ].set( 0, 0, 0 );
  34081. }
  34082. return this;
  34083. }
  34084. /**
  34085. * Returns the radiance in the direction of the given normal.
  34086. *
  34087. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34088. * @param {Vector3} target - The target vector that is used to store the method's result.
  34089. * @return {Vector3} The radiance.
  34090. */
  34091. getAt( normal, target ) {
  34092. // normal is assumed to be unit length
  34093. const x = normal.x, y = normal.y, z = normal.z;
  34094. const coeff = this.coefficients;
  34095. // band 0
  34096. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34097. // band 1
  34098. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34099. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34100. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34101. // band 2
  34102. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34103. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34104. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34105. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34106. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34107. return target;
  34108. }
  34109. /**
  34110. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34111. * direction of the given normal.
  34112. *
  34113. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34114. * @param {Vector3} target - The target vector that is used to store the method's result.
  34115. * @return {Vector3} The irradiance.
  34116. */
  34117. getIrradianceAt( normal, target ) {
  34118. // normal is assumed to be unit length
  34119. const x = normal.x, y = normal.y, z = normal.z;
  34120. const coeff = this.coefficients;
  34121. // band 0
  34122. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34123. // band 1
  34124. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34125. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34126. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34127. // band 2
  34128. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34129. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34130. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34131. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34132. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34133. return target;
  34134. }
  34135. /**
  34136. * Adds the given SH to this instance.
  34137. *
  34138. * @param {SphericalHarmonics3} sh - The SH to add.
  34139. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34140. */
  34141. add( sh ) {
  34142. for ( let i = 0; i < 9; i ++ ) {
  34143. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34144. }
  34145. return this;
  34146. }
  34147. /**
  34148. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34149. * {@link SphericalHarmonics3#scale} at once.
  34150. *
  34151. * @param {SphericalHarmonics3} sh - The SH to add.
  34152. * @param {number} s - The scale factor.
  34153. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34154. */
  34155. addScaledSH( sh, s ) {
  34156. for ( let i = 0; i < 9; i ++ ) {
  34157. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34158. }
  34159. return this;
  34160. }
  34161. /**
  34162. * Scales this SH by the given scale factor.
  34163. *
  34164. * @param {number} s - The scale factor.
  34165. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34166. */
  34167. scale( s ) {
  34168. for ( let i = 0; i < 9; i ++ ) {
  34169. this.coefficients[ i ].multiplyScalar( s );
  34170. }
  34171. return this;
  34172. }
  34173. /**
  34174. * Linear interpolates between the given SH and this instance by the given
  34175. * alpha factor.
  34176. *
  34177. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34178. * @param {number} alpha - The alpha factor.
  34179. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34180. */
  34181. lerp( sh, alpha ) {
  34182. for ( let i = 0; i < 9; i ++ ) {
  34183. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34184. }
  34185. return this;
  34186. }
  34187. /**
  34188. * Returns `true` if this spherical harmonics is equal with the given one.
  34189. *
  34190. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34191. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34192. */
  34193. equals( sh ) {
  34194. for ( let i = 0; i < 9; i ++ ) {
  34195. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34196. return false;
  34197. }
  34198. }
  34199. return true;
  34200. }
  34201. /**
  34202. * Copies the values of the given spherical harmonics to this instance.
  34203. *
  34204. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34205. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34206. */
  34207. copy( sh ) {
  34208. return this.set( sh.coefficients );
  34209. }
  34210. /**
  34211. * Returns a new spherical harmonics with copied values from this instance.
  34212. *
  34213. * @return {SphericalHarmonics3} A clone of this instance.
  34214. */
  34215. clone() {
  34216. return new this.constructor().copy( this );
  34217. }
  34218. /**
  34219. * Sets the SH coefficients of this instance from the given array.
  34220. *
  34221. * @param {Array<number>} array - An array holding the SH coefficients.
  34222. * @param {number} [offset=0] - The array offset where to start copying.
  34223. * @return {SphericalHarmonics3} A clone of this instance.
  34224. */
  34225. fromArray( array, offset = 0 ) {
  34226. const coefficients = this.coefficients;
  34227. for ( let i = 0; i < 9; i ++ ) {
  34228. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34229. }
  34230. return this;
  34231. }
  34232. /**
  34233. * Returns an array with the SH coefficients, or copies them into the provided
  34234. * array. The coefficients are represented as numbers.
  34235. *
  34236. * @param {Array<number>} [array=[]] - The target array.
  34237. * @param {number} [offset=0] - The array offset where to start copying.
  34238. * @return {Array<number>} An array with flat SH coefficients.
  34239. */
  34240. toArray( array = [], offset = 0 ) {
  34241. const coefficients = this.coefficients;
  34242. for ( let i = 0; i < 9; i ++ ) {
  34243. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34244. }
  34245. return array;
  34246. }
  34247. /**
  34248. * Computes the SH basis for the given normal vector.
  34249. *
  34250. * @param {Vector3} normal - The normal.
  34251. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34252. */
  34253. static getBasisAt( normal, shBasis ) {
  34254. // normal is assumed to be unit length
  34255. const x = normal.x, y = normal.y, z = normal.z;
  34256. // band 0
  34257. shBasis[ 0 ] = 0.282095;
  34258. // band 1
  34259. shBasis[ 1 ] = 0.488603 * y;
  34260. shBasis[ 2 ] = 0.488603 * z;
  34261. shBasis[ 3 ] = 0.488603 * x;
  34262. // band 2
  34263. shBasis[ 4 ] = 1.092548 * x * y;
  34264. shBasis[ 5 ] = 1.092548 * y * z;
  34265. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34266. shBasis[ 7 ] = 1.092548 * x * z;
  34267. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34268. }
  34269. }
  34270. /**
  34271. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34272. * classical light sources (e.g. directional, point or spot lights), light
  34273. * probes do not emit light. Instead they store information about light
  34274. * passing through 3D space. During rendering, the light that hits a 3D
  34275. * object is approximated by using the data from the light probe.
  34276. *
  34277. * Light probes are usually created from (radiance) environment maps. The
  34278. * class {@link LightProbeGenerator} can be used to create light probes from
  34279. * cube textures or render targets. However, light estimation data could also
  34280. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34281. * augmented reality content that reacts to real world lighting.
  34282. *
  34283. * The current probe implementation in three.js supports so-called diffuse
  34284. * light probes. This type of light probe is functionally equivalent to an
  34285. * irradiance environment map.
  34286. *
  34287. * @augments Light
  34288. */
  34289. class LightProbe extends Light {
  34290. /**
  34291. * Constructs a new light probe.
  34292. *
  34293. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34294. * @param {number} [intensity=1] - The light's strength/intensity.
  34295. */
  34296. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34297. super( undefined, intensity );
  34298. /**
  34299. * This flag can be used for type testing.
  34300. *
  34301. * @type {boolean}
  34302. * @readonly
  34303. * @default true
  34304. */
  34305. this.isLightProbe = true;
  34306. /**
  34307. * A light probe uses spherical harmonics to encode lighting information.
  34308. *
  34309. * @type {SphericalHarmonics3}
  34310. */
  34311. this.sh = sh;
  34312. }
  34313. copy( source ) {
  34314. super.copy( source );
  34315. this.sh.copy( source.sh );
  34316. return this;
  34317. }
  34318. /**
  34319. * Deserializes the light prove from the given JSON.
  34320. *
  34321. * @param {Object} json - The JSON holding the serialized light probe.
  34322. * @return {LightProbe} A reference to this light probe.
  34323. */
  34324. fromJSON( json ) {
  34325. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  34326. this.sh.fromArray( json.sh );
  34327. return this;
  34328. }
  34329. toJSON( meta ) {
  34330. const data = super.toJSON( meta );
  34331. data.object.sh = this.sh.toArray();
  34332. return data;
  34333. }
  34334. }
  34335. /**
  34336. * Class for loading geometries. The files are internally
  34337. * loaded via {@link FileLoader}.
  34338. *
  34339. * ```js
  34340. * const loader = new THREE.MaterialLoader();
  34341. * const material = await loader.loadAsync( 'material.json' );
  34342. * ```
  34343. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34344. *
  34345. * @augments Loader
  34346. */
  34347. class MaterialLoader extends Loader {
  34348. /**
  34349. * Constructs a new material loader.
  34350. *
  34351. * @param {LoadingManager} [manager] - The loading manager.
  34352. */
  34353. constructor( manager ) {
  34354. super( manager );
  34355. /**
  34356. * A dictionary holding textures used by the material.
  34357. *
  34358. * @type {Object<string,Texture>}
  34359. */
  34360. this.textures = {};
  34361. }
  34362. /**
  34363. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34364. *
  34365. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34366. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34367. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34368. * @param {onErrorCallback} onError - Executed when errors occur.
  34369. */
  34370. load( url, onLoad, onProgress, onError ) {
  34371. const scope = this;
  34372. const loader = new FileLoader( scope.manager );
  34373. loader.setPath( scope.path );
  34374. loader.setRequestHeader( scope.requestHeader );
  34375. loader.setWithCredentials( scope.withCredentials );
  34376. loader.load( url, function ( text ) {
  34377. try {
  34378. onLoad( scope.parse( JSON.parse( text ) ) );
  34379. } catch ( e ) {
  34380. if ( onError ) {
  34381. onError( e );
  34382. } else {
  34383. console.error( e );
  34384. }
  34385. scope.manager.itemError( url );
  34386. }
  34387. }, onProgress, onError );
  34388. }
  34389. /**
  34390. * Parses the given JSON object and returns a material.
  34391. *
  34392. * @param {Object} json - The serialized material.
  34393. * @return {Material} The parsed material.
  34394. */
  34395. parse( json ) {
  34396. const textures = this.textures;
  34397. function getTexture( name ) {
  34398. if ( textures[ name ] === undefined ) {
  34399. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  34400. }
  34401. return textures[ name ];
  34402. }
  34403. const material = this.createMaterialFromType( json.type );
  34404. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34405. if ( json.name !== undefined ) material.name = json.name;
  34406. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34407. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34408. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34409. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34410. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34411. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34412. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34413. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34414. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34415. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34416. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34417. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34418. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34419. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34420. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34421. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34422. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34423. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34424. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34425. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34426. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34427. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34428. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34429. if ( json.fog !== undefined ) material.fog = json.fog;
  34430. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34431. if ( json.blending !== undefined ) material.blending = json.blending;
  34432. if ( json.combine !== undefined ) material.combine = json.combine;
  34433. if ( json.side !== undefined ) material.side = json.side;
  34434. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34435. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34436. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34437. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34438. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34439. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34440. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34441. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34442. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34443. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34444. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34445. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34446. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34447. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34448. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34449. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34450. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34451. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34452. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34453. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34454. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34455. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34456. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34457. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34458. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34459. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34460. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34461. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34462. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34463. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34464. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34465. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34466. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34467. if ( json.scale !== undefined ) material.scale = json.scale;
  34468. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34469. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34470. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34471. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34472. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34473. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34474. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34475. if ( json.visible !== undefined ) material.visible = json.visible;
  34476. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34477. if ( json.userData !== undefined ) material.userData = json.userData;
  34478. if ( json.vertexColors !== undefined ) {
  34479. if ( typeof json.vertexColors === 'number' ) {
  34480. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34481. } else {
  34482. material.vertexColors = json.vertexColors;
  34483. }
  34484. }
  34485. // Shader Material
  34486. if ( json.uniforms !== undefined ) {
  34487. for ( const name in json.uniforms ) {
  34488. const uniform = json.uniforms[ name ];
  34489. material.uniforms[ name ] = {};
  34490. switch ( uniform.type ) {
  34491. case 't':
  34492. material.uniforms[ name ].value = getTexture( uniform.value );
  34493. break;
  34494. case 'c':
  34495. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34496. break;
  34497. case 'v2':
  34498. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34499. break;
  34500. case 'v3':
  34501. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34502. break;
  34503. case 'v4':
  34504. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34505. break;
  34506. case 'm3':
  34507. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34508. break;
  34509. case 'm4':
  34510. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34511. break;
  34512. default:
  34513. material.uniforms[ name ].value = uniform.value;
  34514. }
  34515. }
  34516. }
  34517. if ( json.defines !== undefined ) material.defines = json.defines;
  34518. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34519. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34520. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34521. if ( json.extensions !== undefined ) {
  34522. for ( const key in json.extensions ) {
  34523. material.extensions[ key ] = json.extensions[ key ];
  34524. }
  34525. }
  34526. if ( json.lights !== undefined ) material.lights = json.lights;
  34527. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34528. // for PointsMaterial
  34529. if ( json.size !== undefined ) material.size = json.size;
  34530. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34531. // maps
  34532. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34533. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34534. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34535. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34536. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34537. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34538. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34539. if ( json.normalScale !== undefined ) {
  34540. let normalScale = json.normalScale;
  34541. if ( Array.isArray( normalScale ) === false ) {
  34542. // Blender exporter used to export a scalar. See #7459
  34543. normalScale = [ normalScale, normalScale ];
  34544. }
  34545. material.normalScale = new Vector2().fromArray( normalScale );
  34546. }
  34547. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34548. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34549. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34550. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34551. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34552. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34553. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34554. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34555. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34556. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34557. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34558. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34559. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34560. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34561. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34562. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34563. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34564. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34565. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34566. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34567. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34568. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34569. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34570. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34571. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34572. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34573. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34574. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34575. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34576. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34577. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34578. return material;
  34579. }
  34580. /**
  34581. * Textures are not embedded in the material JSON so they have
  34582. * to be injected before the loading process starts.
  34583. *
  34584. * @param {Object} value - A dictionary holding textures for material properties.
  34585. * @return {MaterialLoader} A reference to this material loader.
  34586. */
  34587. setTextures( value ) {
  34588. this.textures = value;
  34589. return this;
  34590. }
  34591. /**
  34592. * Creates a material for the given type.
  34593. *
  34594. * @param {string} type - The material type.
  34595. * @return {Material} The new material.
  34596. */
  34597. createMaterialFromType( type ) {
  34598. return MaterialLoader.createMaterialFromType( type );
  34599. }
  34600. /**
  34601. * Creates a material for the given type.
  34602. *
  34603. * @static
  34604. * @param {string} type - The material type.
  34605. * @return {Material} The new material.
  34606. */
  34607. static createMaterialFromType( type ) {
  34608. const materialLib = {
  34609. ShadowMaterial,
  34610. SpriteMaterial,
  34611. RawShaderMaterial,
  34612. ShaderMaterial,
  34613. PointsMaterial,
  34614. MeshPhysicalMaterial,
  34615. MeshStandardMaterial,
  34616. MeshPhongMaterial,
  34617. MeshToonMaterial,
  34618. MeshNormalMaterial,
  34619. MeshLambertMaterial,
  34620. MeshDepthMaterial,
  34621. MeshDistanceMaterial,
  34622. MeshBasicMaterial,
  34623. MeshMatcapMaterial,
  34624. LineDashedMaterial,
  34625. LineBasicMaterial,
  34626. Material
  34627. };
  34628. return new materialLib[ type ]();
  34629. }
  34630. }
  34631. /**
  34632. * A class with loader utility functions.
  34633. */
  34634. class LoaderUtils {
  34635. /**
  34636. * Extracts the base URL from the given URL.
  34637. *
  34638. * @param {string} url -The URL to extract the base URL from.
  34639. * @return {string} The extracted base URL.
  34640. */
  34641. static extractUrlBase( url ) {
  34642. const index = url.lastIndexOf( '/' );
  34643. if ( index === -1 ) return './';
  34644. return url.slice( 0, index + 1 );
  34645. }
  34646. /**
  34647. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34648. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34649. * string.
  34650. *
  34651. * @param {string} url -The URL to resolve.
  34652. * @param {string} path - The base path for relative URLs to be resolved against.
  34653. * @return {string} The resolved URL.
  34654. */
  34655. static resolveURL( url, path ) {
  34656. // Invalid URL
  34657. if ( typeof url !== 'string' || url === '' ) return '';
  34658. // Host Relative URL
  34659. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34660. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34661. }
  34662. // Absolute URL http://,https://,//
  34663. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34664. // Data URI
  34665. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34666. // Blob URL
  34667. if ( /^blob:.*$/i.test( url ) ) return url;
  34668. // Relative URL
  34669. return path + url;
  34670. }
  34671. }
  34672. /**
  34673. * An instanced version of a geometry.
  34674. */
  34675. class InstancedBufferGeometry extends BufferGeometry {
  34676. /**
  34677. * Constructs a new instanced buffer geometry.
  34678. */
  34679. constructor() {
  34680. super();
  34681. /**
  34682. * This flag can be used for type testing.
  34683. *
  34684. * @type {boolean}
  34685. * @readonly
  34686. * @default true
  34687. */
  34688. this.isInstancedBufferGeometry = true;
  34689. this.type = 'InstancedBufferGeometry';
  34690. /**
  34691. * The instance count.
  34692. *
  34693. * @type {number}
  34694. * @default Infinity
  34695. */
  34696. this.instanceCount = Infinity;
  34697. }
  34698. copy( source ) {
  34699. super.copy( source );
  34700. this.instanceCount = source.instanceCount;
  34701. return this;
  34702. }
  34703. toJSON() {
  34704. const data = super.toJSON();
  34705. data.instanceCount = this.instanceCount;
  34706. data.isInstancedBufferGeometry = true;
  34707. return data;
  34708. }
  34709. }
  34710. /**
  34711. * Class for loading geometries. The files are internally
  34712. * loaded via {@link FileLoader}.
  34713. *
  34714. * ```js
  34715. * const loader = new THREE.BufferGeometryLoader();
  34716. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34717. *
  34718. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34719. * const object = new THREE.Mesh( geometry, material );
  34720. * scene.add( object );
  34721. * ```
  34722. *
  34723. * @augments Loader
  34724. */
  34725. class BufferGeometryLoader extends Loader {
  34726. /**
  34727. * Constructs a new geometry loader.
  34728. *
  34729. * @param {LoadingManager} [manager] - The loading manager.
  34730. */
  34731. constructor( manager ) {
  34732. super( manager );
  34733. }
  34734. /**
  34735. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34736. *
  34737. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34738. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34739. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34740. * @param {onErrorCallback} onError - Executed when errors occur.
  34741. */
  34742. load( url, onLoad, onProgress, onError ) {
  34743. const scope = this;
  34744. const loader = new FileLoader( scope.manager );
  34745. loader.setPath( scope.path );
  34746. loader.setRequestHeader( scope.requestHeader );
  34747. loader.setWithCredentials( scope.withCredentials );
  34748. loader.load( url, function ( text ) {
  34749. try {
  34750. onLoad( scope.parse( JSON.parse( text ) ) );
  34751. } catch ( e ) {
  34752. if ( onError ) {
  34753. onError( e );
  34754. } else {
  34755. console.error( e );
  34756. }
  34757. scope.manager.itemError( url );
  34758. }
  34759. }, onProgress, onError );
  34760. }
  34761. /**
  34762. * Parses the given JSON object and returns a geometry.
  34763. *
  34764. * @param {Object} json - The serialized geometry.
  34765. * @return {BufferGeometry} The parsed geometry.
  34766. */
  34767. parse( json ) {
  34768. const interleavedBufferMap = {};
  34769. const arrayBufferMap = {};
  34770. function getInterleavedBuffer( json, uuid ) {
  34771. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34772. const interleavedBuffers = json.interleavedBuffers;
  34773. const interleavedBuffer = interleavedBuffers[ uuid ];
  34774. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34775. const array = getTypedArray( interleavedBuffer.type, buffer );
  34776. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34777. ib.uuid = interleavedBuffer.uuid;
  34778. interleavedBufferMap[ uuid ] = ib;
  34779. return ib;
  34780. }
  34781. function getArrayBuffer( json, uuid ) {
  34782. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34783. const arrayBuffers = json.arrayBuffers;
  34784. const arrayBuffer = arrayBuffers[ uuid ];
  34785. const ab = new Uint32Array( arrayBuffer ).buffer;
  34786. arrayBufferMap[ uuid ] = ab;
  34787. return ab;
  34788. }
  34789. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34790. const index = json.data.index;
  34791. if ( index !== undefined ) {
  34792. const typedArray = getTypedArray( index.type, index.array );
  34793. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34794. }
  34795. const attributes = json.data.attributes;
  34796. for ( const key in attributes ) {
  34797. const attribute = attributes[ key ];
  34798. let bufferAttribute;
  34799. if ( attribute.isInterleavedBufferAttribute ) {
  34800. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34801. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34802. } else {
  34803. const typedArray = getTypedArray( attribute.type, attribute.array );
  34804. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34805. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  34806. }
  34807. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34808. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  34809. geometry.setAttribute( key, bufferAttribute );
  34810. }
  34811. const morphAttributes = json.data.morphAttributes;
  34812. if ( morphAttributes ) {
  34813. for ( const key in morphAttributes ) {
  34814. const attributeArray = morphAttributes[ key ];
  34815. const array = [];
  34816. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  34817. const attribute = attributeArray[ i ];
  34818. let bufferAttribute;
  34819. if ( attribute.isInterleavedBufferAttribute ) {
  34820. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34821. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34822. } else {
  34823. const typedArray = getTypedArray( attribute.type, attribute.array );
  34824. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  34825. }
  34826. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34827. array.push( bufferAttribute );
  34828. }
  34829. geometry.morphAttributes[ key ] = array;
  34830. }
  34831. }
  34832. const morphTargetsRelative = json.data.morphTargetsRelative;
  34833. if ( morphTargetsRelative ) {
  34834. geometry.morphTargetsRelative = true;
  34835. }
  34836. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  34837. if ( groups !== undefined ) {
  34838. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  34839. const group = groups[ i ];
  34840. geometry.addGroup( group.start, group.count, group.materialIndex );
  34841. }
  34842. }
  34843. const boundingSphere = json.data.boundingSphere;
  34844. if ( boundingSphere !== undefined ) {
  34845. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  34846. }
  34847. if ( json.name ) geometry.name = json.name;
  34848. if ( json.userData ) geometry.userData = json.userData;
  34849. return geometry;
  34850. }
  34851. }
  34852. /**
  34853. * A loader for loading a JSON resource in the [JSON Object/Scene format]{@link https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4}.
  34854. * The files are internally loaded via {@link FileLoader}.
  34855. *
  34856. * ```js
  34857. * const loader = new THREE.ObjectLoader();
  34858. * const obj = await loader.loadAsync( 'models/json/example.json' );
  34859. * scene.add( obj );
  34860. *
  34861. * // Alternatively, to parse a previously loaded JSON structure
  34862. * const object = await loader.parseAsync( a_json_object );
  34863. * scene.add( object );
  34864. * ```
  34865. *
  34866. * @augments Loader
  34867. */
  34868. class ObjectLoader extends Loader {
  34869. /**
  34870. * Constructs a new object loader.
  34871. *
  34872. * @param {LoadingManager} [manager] - The loading manager.
  34873. */
  34874. constructor( manager ) {
  34875. super( manager );
  34876. }
  34877. /**
  34878. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  34879. *
  34880. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34881. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  34882. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34883. * @param {onErrorCallback} onError - Executed when errors occur.
  34884. */
  34885. load( url, onLoad, onProgress, onError ) {
  34886. const scope = this;
  34887. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34888. this.resourcePath = this.resourcePath || path;
  34889. const loader = new FileLoader( this.manager );
  34890. loader.setPath( this.path );
  34891. loader.setRequestHeader( this.requestHeader );
  34892. loader.setWithCredentials( this.withCredentials );
  34893. loader.load( url, function ( text ) {
  34894. let json = null;
  34895. try {
  34896. json = JSON.parse( text );
  34897. } catch ( error ) {
  34898. if ( onError !== undefined ) onError( error );
  34899. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  34900. return;
  34901. }
  34902. const metadata = json.metadata;
  34903. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34904. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  34905. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34906. return;
  34907. }
  34908. scope.parse( json, onLoad );
  34909. }, onProgress, onError );
  34910. }
  34911. /**
  34912. * Async version of {@link ObjectLoader#load}.
  34913. *
  34914. * @async
  34915. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34916. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34917. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  34918. */
  34919. async loadAsync( url, onProgress ) {
  34920. const scope = this;
  34921. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34922. this.resourcePath = this.resourcePath || path;
  34923. const loader = new FileLoader( this.manager );
  34924. loader.setPath( this.path );
  34925. loader.setRequestHeader( this.requestHeader );
  34926. loader.setWithCredentials( this.withCredentials );
  34927. const text = await loader.loadAsync( url, onProgress );
  34928. const json = JSON.parse( text );
  34929. const metadata = json.metadata;
  34930. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34931. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34932. }
  34933. return await scope.parseAsync( json );
  34934. }
  34935. /**
  34936. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  34937. * but can also be used directly to parse a previously loaded JSON structure.
  34938. *
  34939. * @param {Object} json - The serialized 3D object.
  34940. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  34941. * @return {Object3D} The parsed 3D object.
  34942. */
  34943. parse( json, onLoad ) {
  34944. const animations = this.parseAnimations( json.animations );
  34945. const shapes = this.parseShapes( json.shapes );
  34946. const geometries = this.parseGeometries( json.geometries, shapes );
  34947. const images = this.parseImages( json.images, function () {
  34948. if ( onLoad !== undefined ) onLoad( object );
  34949. } );
  34950. const textures = this.parseTextures( json.textures, images );
  34951. const materials = this.parseMaterials( json.materials, textures );
  34952. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34953. const skeletons = this.parseSkeletons( json.skeletons, object );
  34954. this.bindSkeletons( object, skeletons );
  34955. this.bindLightTargets( object );
  34956. //
  34957. if ( onLoad !== undefined ) {
  34958. let hasImages = false;
  34959. for ( const uuid in images ) {
  34960. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  34961. hasImages = true;
  34962. break;
  34963. }
  34964. }
  34965. if ( hasImages === false ) onLoad( object );
  34966. }
  34967. return object;
  34968. }
  34969. /**
  34970. * Async version of {@link ObjectLoader#parse}.
  34971. *
  34972. * @param {Object} json - The serialized 3D object.
  34973. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  34974. */
  34975. async parseAsync( json ) {
  34976. const animations = this.parseAnimations( json.animations );
  34977. const shapes = this.parseShapes( json.shapes );
  34978. const geometries = this.parseGeometries( json.geometries, shapes );
  34979. const images = await this.parseImagesAsync( json.images );
  34980. const textures = this.parseTextures( json.textures, images );
  34981. const materials = this.parseMaterials( json.materials, textures );
  34982. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34983. const skeletons = this.parseSkeletons( json.skeletons, object );
  34984. this.bindSkeletons( object, skeletons );
  34985. this.bindLightTargets( object );
  34986. return object;
  34987. }
  34988. // internals
  34989. parseShapes( json ) {
  34990. const shapes = {};
  34991. if ( json !== undefined ) {
  34992. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34993. const shape = new Shape().fromJSON( json[ i ] );
  34994. shapes[ shape.uuid ] = shape;
  34995. }
  34996. }
  34997. return shapes;
  34998. }
  34999. parseSkeletons( json, object ) {
  35000. const skeletons = {};
  35001. const bones = {};
  35002. // generate bone lookup table
  35003. object.traverse( function ( child ) {
  35004. if ( child.isBone ) bones[ child.uuid ] = child;
  35005. } );
  35006. // create skeletons
  35007. if ( json !== undefined ) {
  35008. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35009. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35010. skeletons[ skeleton.uuid ] = skeleton;
  35011. }
  35012. }
  35013. return skeletons;
  35014. }
  35015. parseGeometries( json, shapes ) {
  35016. const geometries = {};
  35017. if ( json !== undefined ) {
  35018. const bufferGeometryLoader = new BufferGeometryLoader();
  35019. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35020. let geometry;
  35021. const data = json[ i ];
  35022. switch ( data.type ) {
  35023. case 'BufferGeometry':
  35024. case 'InstancedBufferGeometry':
  35025. geometry = bufferGeometryLoader.parse( data );
  35026. break;
  35027. default:
  35028. if ( data.type in Geometries ) {
  35029. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35030. } else {
  35031. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35032. }
  35033. }
  35034. geometry.uuid = data.uuid;
  35035. if ( data.name !== undefined ) geometry.name = data.name;
  35036. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35037. geometries[ data.uuid ] = geometry;
  35038. }
  35039. }
  35040. return geometries;
  35041. }
  35042. parseMaterials( json, textures ) {
  35043. const cache = {}; // MultiMaterial
  35044. const materials = {};
  35045. if ( json !== undefined ) {
  35046. const loader = new MaterialLoader();
  35047. loader.setTextures( textures );
  35048. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35049. const data = json[ i ];
  35050. if ( cache[ data.uuid ] === undefined ) {
  35051. cache[ data.uuid ] = loader.parse( data );
  35052. }
  35053. materials[ data.uuid ] = cache[ data.uuid ];
  35054. }
  35055. }
  35056. return materials;
  35057. }
  35058. parseAnimations( json ) {
  35059. const animations = {};
  35060. if ( json !== undefined ) {
  35061. for ( let i = 0; i < json.length; i ++ ) {
  35062. const data = json[ i ];
  35063. const clip = AnimationClip.parse( data );
  35064. animations[ clip.uuid ] = clip;
  35065. }
  35066. }
  35067. return animations;
  35068. }
  35069. parseImages( json, onLoad ) {
  35070. const scope = this;
  35071. const images = {};
  35072. let loader;
  35073. function loadImage( url ) {
  35074. scope.manager.itemStart( url );
  35075. return loader.load( url, function () {
  35076. scope.manager.itemEnd( url );
  35077. }, undefined, function () {
  35078. scope.manager.itemError( url );
  35079. scope.manager.itemEnd( url );
  35080. } );
  35081. }
  35082. function deserializeImage( image ) {
  35083. if ( typeof image === 'string' ) {
  35084. const url = image;
  35085. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35086. return loadImage( path );
  35087. } else {
  35088. if ( image.data ) {
  35089. return {
  35090. data: getTypedArray( image.type, image.data ),
  35091. width: image.width,
  35092. height: image.height
  35093. };
  35094. } else {
  35095. return null;
  35096. }
  35097. }
  35098. }
  35099. if ( json !== undefined && json.length > 0 ) {
  35100. const manager = new LoadingManager( onLoad );
  35101. loader = new ImageLoader( manager );
  35102. loader.setCrossOrigin( this.crossOrigin );
  35103. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35104. const image = json[ i ];
  35105. const url = image.url;
  35106. if ( Array.isArray( url ) ) {
  35107. // load array of images e.g CubeTexture
  35108. const imageArray = [];
  35109. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35110. const currentUrl = url[ j ];
  35111. const deserializedImage = deserializeImage( currentUrl );
  35112. if ( deserializedImage !== null ) {
  35113. if ( deserializedImage instanceof HTMLImageElement ) {
  35114. imageArray.push( deserializedImage );
  35115. } else {
  35116. // special case: handle array of data textures for cube textures
  35117. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35118. }
  35119. }
  35120. }
  35121. images[ image.uuid ] = new Source( imageArray );
  35122. } else {
  35123. // load single image
  35124. const deserializedImage = deserializeImage( image.url );
  35125. images[ image.uuid ] = new Source( deserializedImage );
  35126. }
  35127. }
  35128. }
  35129. return images;
  35130. }
  35131. async parseImagesAsync( json ) {
  35132. const scope = this;
  35133. const images = {};
  35134. let loader;
  35135. async function deserializeImage( image ) {
  35136. if ( typeof image === 'string' ) {
  35137. const url = image;
  35138. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35139. return await loader.loadAsync( path );
  35140. } else {
  35141. if ( image.data ) {
  35142. return {
  35143. data: getTypedArray( image.type, image.data ),
  35144. width: image.width,
  35145. height: image.height
  35146. };
  35147. } else {
  35148. return null;
  35149. }
  35150. }
  35151. }
  35152. if ( json !== undefined && json.length > 0 ) {
  35153. loader = new ImageLoader( this.manager );
  35154. loader.setCrossOrigin( this.crossOrigin );
  35155. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35156. const image = json[ i ];
  35157. const url = image.url;
  35158. if ( Array.isArray( url ) ) {
  35159. // load array of images e.g CubeTexture
  35160. const imageArray = [];
  35161. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35162. const currentUrl = url[ j ];
  35163. const deserializedImage = await deserializeImage( currentUrl );
  35164. if ( deserializedImage !== null ) {
  35165. if ( deserializedImage instanceof HTMLImageElement ) {
  35166. imageArray.push( deserializedImage );
  35167. } else {
  35168. // special case: handle array of data textures for cube textures
  35169. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35170. }
  35171. }
  35172. }
  35173. images[ image.uuid ] = new Source( imageArray );
  35174. } else {
  35175. // load single image
  35176. const deserializedImage = await deserializeImage( image.url );
  35177. images[ image.uuid ] = new Source( deserializedImage );
  35178. }
  35179. }
  35180. }
  35181. return images;
  35182. }
  35183. parseTextures( json, images ) {
  35184. function parseConstant( value, type ) {
  35185. if ( typeof value === 'number' ) return value;
  35186. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35187. return type[ value ];
  35188. }
  35189. const textures = {};
  35190. if ( json !== undefined ) {
  35191. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35192. const data = json[ i ];
  35193. if ( data.image === undefined ) {
  35194. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  35195. }
  35196. if ( images[ data.image ] === undefined ) {
  35197. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  35198. }
  35199. const source = images[ data.image ];
  35200. const image = source.data;
  35201. let texture;
  35202. if ( Array.isArray( image ) ) {
  35203. texture = new CubeTexture();
  35204. if ( image.length === 6 ) texture.needsUpdate = true;
  35205. } else {
  35206. if ( image && image.data ) {
  35207. texture = new DataTexture();
  35208. } else {
  35209. texture = new Texture();
  35210. }
  35211. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35212. }
  35213. texture.source = source;
  35214. texture.uuid = data.uuid;
  35215. if ( data.name !== undefined ) texture.name = data.name;
  35216. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35217. if ( data.channel !== undefined ) texture.channel = data.channel;
  35218. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35219. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35220. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35221. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35222. if ( data.wrap !== undefined ) {
  35223. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35224. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35225. }
  35226. if ( data.format !== undefined ) texture.format = data.format;
  35227. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35228. if ( data.type !== undefined ) texture.type = data.type;
  35229. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35230. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35231. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35232. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35233. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35234. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35235. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35236. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35237. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35238. if ( data.userData !== undefined ) texture.userData = data.userData;
  35239. textures[ data.uuid ] = texture;
  35240. }
  35241. }
  35242. return textures;
  35243. }
  35244. parseObject( data, geometries, materials, textures, animations ) {
  35245. let object;
  35246. function getGeometry( name ) {
  35247. if ( geometries[ name ] === undefined ) {
  35248. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  35249. }
  35250. return geometries[ name ];
  35251. }
  35252. function getMaterial( name ) {
  35253. if ( name === undefined ) return undefined;
  35254. if ( Array.isArray( name ) ) {
  35255. const array = [];
  35256. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35257. const uuid = name[ i ];
  35258. if ( materials[ uuid ] === undefined ) {
  35259. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  35260. }
  35261. array.push( materials[ uuid ] );
  35262. }
  35263. return array;
  35264. }
  35265. if ( materials[ name ] === undefined ) {
  35266. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  35267. }
  35268. return materials[ name ];
  35269. }
  35270. function getTexture( uuid ) {
  35271. if ( textures[ uuid ] === undefined ) {
  35272. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  35273. }
  35274. return textures[ uuid ];
  35275. }
  35276. let geometry, material;
  35277. switch ( data.type ) {
  35278. case 'Scene':
  35279. object = new Scene();
  35280. if ( data.background !== undefined ) {
  35281. if ( Number.isInteger( data.background ) ) {
  35282. object.background = new Color( data.background );
  35283. } else {
  35284. object.background = getTexture( data.background );
  35285. }
  35286. }
  35287. if ( data.environment !== undefined ) {
  35288. object.environment = getTexture( data.environment );
  35289. }
  35290. if ( data.fog !== undefined ) {
  35291. if ( data.fog.type === 'Fog' ) {
  35292. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35293. } else if ( data.fog.type === 'FogExp2' ) {
  35294. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35295. }
  35296. if ( data.fog.name !== '' ) {
  35297. object.fog.name = data.fog.name;
  35298. }
  35299. }
  35300. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35301. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35302. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35303. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35304. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35305. break;
  35306. case 'PerspectiveCamera':
  35307. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35308. if ( data.focus !== undefined ) object.focus = data.focus;
  35309. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35310. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35311. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35312. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35313. break;
  35314. case 'OrthographicCamera':
  35315. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35316. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35317. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35318. break;
  35319. case 'AmbientLight':
  35320. object = new AmbientLight( data.color, data.intensity );
  35321. break;
  35322. case 'DirectionalLight':
  35323. object = new DirectionalLight( data.color, data.intensity );
  35324. object.target = data.target || '';
  35325. break;
  35326. case 'PointLight':
  35327. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35328. break;
  35329. case 'RectAreaLight':
  35330. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35331. break;
  35332. case 'SpotLight':
  35333. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35334. object.target = data.target || '';
  35335. break;
  35336. case 'HemisphereLight':
  35337. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35338. break;
  35339. case 'LightProbe':
  35340. object = new LightProbe().fromJSON( data );
  35341. break;
  35342. case 'SkinnedMesh':
  35343. geometry = getGeometry( data.geometry );
  35344. material = getMaterial( data.material );
  35345. object = new SkinnedMesh( geometry, material );
  35346. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35347. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35348. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35349. break;
  35350. case 'Mesh':
  35351. geometry = getGeometry( data.geometry );
  35352. material = getMaterial( data.material );
  35353. object = new Mesh( geometry, material );
  35354. break;
  35355. case 'InstancedMesh':
  35356. geometry = getGeometry( data.geometry );
  35357. material = getMaterial( data.material );
  35358. const count = data.count;
  35359. const instanceMatrix = data.instanceMatrix;
  35360. const instanceColor = data.instanceColor;
  35361. object = new InstancedMesh( geometry, material, count );
  35362. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35363. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35364. break;
  35365. case 'BatchedMesh':
  35366. geometry = getGeometry( data.geometry );
  35367. material = getMaterial( data.material );
  35368. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35369. object.geometry = geometry;
  35370. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35371. object.sortObjects = data.sortObjects;
  35372. object._drawRanges = data.drawRanges;
  35373. object._reservedRanges = data.reservedRanges;
  35374. object._geometryInfo = data.geometryInfo.map( info => {
  35375. let box = null;
  35376. let sphere = null;
  35377. if ( info.boundingBox !== undefined ) {
  35378. box = new Box3().fromJSON( info.boundingBox );
  35379. }
  35380. if ( info.boundingSphere !== undefined ) {
  35381. sphere = new Sphere().fromJSON( info.boundingSphere );
  35382. }
  35383. return {
  35384. ...info,
  35385. boundingBox: box,
  35386. boundingSphere: sphere
  35387. };
  35388. } );
  35389. object._instanceInfo = data.instanceInfo;
  35390. object._availableInstanceIds = data._availableInstanceIds;
  35391. object._availableGeometryIds = data._availableGeometryIds;
  35392. object._nextIndexStart = data.nextIndexStart;
  35393. object._nextVertexStart = data.nextVertexStart;
  35394. object._geometryCount = data.geometryCount;
  35395. object._maxInstanceCount = data.maxInstanceCount;
  35396. object._maxVertexCount = data.maxVertexCount;
  35397. object._maxIndexCount = data.maxIndexCount;
  35398. object._geometryInitialized = data.geometryInitialized;
  35399. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35400. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35401. if ( data.colorsTexture !== undefined ) {
  35402. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35403. }
  35404. if ( data.boundingSphere !== undefined ) {
  35405. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35406. }
  35407. if ( data.boundingBox !== undefined ) {
  35408. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35409. }
  35410. break;
  35411. case 'LOD':
  35412. object = new LOD();
  35413. break;
  35414. case 'Line':
  35415. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35416. break;
  35417. case 'LineLoop':
  35418. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35419. break;
  35420. case 'LineSegments':
  35421. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35422. break;
  35423. case 'PointCloud':
  35424. case 'Points':
  35425. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35426. break;
  35427. case 'Sprite':
  35428. object = new Sprite( getMaterial( data.material ) );
  35429. break;
  35430. case 'Group':
  35431. object = new Group();
  35432. break;
  35433. case 'Bone':
  35434. object = new Bone();
  35435. break;
  35436. default:
  35437. object = new Object3D();
  35438. }
  35439. object.uuid = data.uuid;
  35440. if ( data.name !== undefined ) object.name = data.name;
  35441. if ( data.matrix !== undefined ) {
  35442. object.matrix.fromArray( data.matrix );
  35443. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35444. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35445. } else {
  35446. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35447. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35448. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35449. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35450. }
  35451. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35452. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35453. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35454. if ( data.shadow ) {
  35455. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35456. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35457. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35458. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35459. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35460. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35461. }
  35462. if ( data.visible !== undefined ) object.visible = data.visible;
  35463. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35464. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35465. if ( data.userData !== undefined ) object.userData = data.userData;
  35466. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35467. if ( data.children !== undefined ) {
  35468. const children = data.children;
  35469. for ( let i = 0; i < children.length; i ++ ) {
  35470. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35471. }
  35472. }
  35473. if ( data.animations !== undefined ) {
  35474. const objectAnimations = data.animations;
  35475. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35476. const uuid = objectAnimations[ i ];
  35477. object.animations.push( animations[ uuid ] );
  35478. }
  35479. }
  35480. if ( data.type === 'LOD' ) {
  35481. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35482. const levels = data.levels;
  35483. for ( let l = 0; l < levels.length; l ++ ) {
  35484. const level = levels[ l ];
  35485. const child = object.getObjectByProperty( 'uuid', level.object );
  35486. if ( child !== undefined ) {
  35487. object.addLevel( child, level.distance, level.hysteresis );
  35488. }
  35489. }
  35490. }
  35491. return object;
  35492. }
  35493. bindSkeletons( object, skeletons ) {
  35494. if ( Object.keys( skeletons ).length === 0 ) return;
  35495. object.traverse( function ( child ) {
  35496. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35497. const skeleton = skeletons[ child.skeleton ];
  35498. if ( skeleton === undefined ) {
  35499. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35500. } else {
  35501. child.bind( skeleton, child.bindMatrix );
  35502. }
  35503. }
  35504. } );
  35505. }
  35506. bindLightTargets( object ) {
  35507. object.traverse( function ( child ) {
  35508. if ( child.isDirectionalLight || child.isSpotLight ) {
  35509. const uuid = child.target;
  35510. const target = object.getObjectByProperty( 'uuid', uuid );
  35511. if ( target !== undefined ) {
  35512. child.target = target;
  35513. } else {
  35514. child.target = new Object3D();
  35515. }
  35516. }
  35517. } );
  35518. }
  35519. }
  35520. const TEXTURE_MAPPING = {
  35521. UVMapping: UVMapping,
  35522. CubeReflectionMapping: CubeReflectionMapping,
  35523. CubeRefractionMapping: CubeRefractionMapping,
  35524. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35525. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35526. CubeUVReflectionMapping: CubeUVReflectionMapping
  35527. };
  35528. const TEXTURE_WRAPPING = {
  35529. RepeatWrapping: RepeatWrapping,
  35530. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35531. MirroredRepeatWrapping: MirroredRepeatWrapping
  35532. };
  35533. const TEXTURE_FILTER = {
  35534. NearestFilter: NearestFilter,
  35535. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35536. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35537. LinearFilter: LinearFilter,
  35538. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35539. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35540. };
  35541. const _errorMap = new WeakMap();
  35542. /**
  35543. * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}.
  35544. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35545. * textures for rendering.
  35546. *
  35547. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35548. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  35549. *
  35550. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  35551. *
  35552. * Also note that unlike {@link FileLoader}, this loader avoids multiple concurrent requests to the same URL only if `Cache` is enabled.
  35553. *
  35554. * ```js
  35555. * const loader = new THREE.ImageBitmapLoader();
  35556. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35557. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35558. *
  35559. * const texture = new THREE.Texture( imageBitmap );
  35560. * texture.needsUpdate = true;
  35561. * ```
  35562. *
  35563. * @augments Loader
  35564. */
  35565. class ImageBitmapLoader extends Loader {
  35566. /**
  35567. * Constructs a new image bitmap loader.
  35568. *
  35569. * @param {LoadingManager} [manager] - The loading manager.
  35570. */
  35571. constructor( manager ) {
  35572. super( manager );
  35573. /**
  35574. * This flag can be used for type testing.
  35575. *
  35576. * @type {boolean}
  35577. * @readonly
  35578. * @default true
  35579. */
  35580. this.isImageBitmapLoader = true;
  35581. if ( typeof createImageBitmap === 'undefined' ) {
  35582. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  35583. }
  35584. if ( typeof fetch === 'undefined' ) {
  35585. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  35586. }
  35587. /**
  35588. * Represents the loader options.
  35589. *
  35590. * @type {Object}
  35591. * @default {premultiplyAlpha:'none'}
  35592. */
  35593. this.options = { premultiplyAlpha: 'none' };
  35594. /**
  35595. * Used for aborting requests.
  35596. *
  35597. * @private
  35598. * @type {AbortController}
  35599. */
  35600. this._abortController = new AbortController();
  35601. }
  35602. /**
  35603. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35604. * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
  35605. *
  35606. * @param {Object} options - The loader options to set.
  35607. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35608. */
  35609. setOptions( options ) {
  35610. this.options = options;
  35611. return this;
  35612. }
  35613. /**
  35614. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35615. *
  35616. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35617. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35618. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35619. * @param {onErrorCallback} onError - Executed when errors occur.
  35620. * @return {ImageBitmap|undefined} The image bitmap.
  35621. */
  35622. load( url, onLoad, onProgress, onError ) {
  35623. if ( url === undefined ) url = '';
  35624. if ( this.path !== undefined ) url = this.path + url;
  35625. url = this.manager.resolveURL( url );
  35626. const scope = this;
  35627. const cached = Cache.get( `image-bitmap:${url}` );
  35628. if ( cached !== undefined ) {
  35629. scope.manager.itemStart( url );
  35630. // If cached is a promise, wait for it to resolve
  35631. if ( cached.then ) {
  35632. cached.then( imageBitmap => {
  35633. // check if there is an error for the cached promise
  35634. if ( _errorMap.has( cached ) === true ) {
  35635. if ( onError ) onError( _errorMap.get( cached ) );
  35636. scope.manager.itemError( url );
  35637. scope.manager.itemEnd( url );
  35638. } else {
  35639. if ( onLoad ) onLoad( imageBitmap );
  35640. scope.manager.itemEnd( url );
  35641. return imageBitmap;
  35642. }
  35643. } );
  35644. return;
  35645. }
  35646. // If cached is not a promise (i.e., it's already an imageBitmap)
  35647. setTimeout( function () {
  35648. if ( onLoad ) onLoad( cached );
  35649. scope.manager.itemEnd( url );
  35650. }, 0 );
  35651. return cached;
  35652. }
  35653. const fetchOptions = {};
  35654. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35655. fetchOptions.headers = this.requestHeader;
  35656. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35657. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35658. return res.blob();
  35659. } ).then( function ( blob ) {
  35660. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35661. } ).then( function ( imageBitmap ) {
  35662. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35663. if ( onLoad ) onLoad( imageBitmap );
  35664. scope.manager.itemEnd( url );
  35665. return imageBitmap;
  35666. } ).catch( function ( e ) {
  35667. if ( onError ) onError( e );
  35668. _errorMap.set( promise, e );
  35669. Cache.remove( `image-bitmap:${url}` );
  35670. scope.manager.itemError( url );
  35671. scope.manager.itemEnd( url );
  35672. } );
  35673. Cache.add( `image-bitmap:${url}`, promise );
  35674. scope.manager.itemStart( url );
  35675. }
  35676. /**
  35677. * Aborts ongoing fetch requests.
  35678. *
  35679. * @return {ImageBitmapLoader} A reference to this instance.
  35680. */
  35681. abort() {
  35682. this._abortController.abort();
  35683. this._abortController = new AbortController();
  35684. return this;
  35685. }
  35686. }
  35687. let _context;
  35688. /**
  35689. * Manages the global audio context in the engine.
  35690. *
  35691. * @hideconstructor
  35692. */
  35693. class AudioContext {
  35694. /**
  35695. * Returns the global native audio context.
  35696. *
  35697. * @return {AudioContext} The native audio context.
  35698. */
  35699. static getContext() {
  35700. if ( _context === undefined ) {
  35701. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35702. }
  35703. return _context;
  35704. }
  35705. /**
  35706. * Allows to set the global native audio context from outside.
  35707. *
  35708. * @param {AudioContext} value - The native context to set.
  35709. */
  35710. static setContext( value ) {
  35711. _context = value;
  35712. }
  35713. }
  35714. /**
  35715. * Class for loading audio buffers. Audios are internally
  35716. * loaded via {@link FileLoader}.
  35717. *
  35718. * ```js
  35719. * const audioListener = new THREE.AudioListener();
  35720. * const ambientSound = new THREE.Audio( audioListener );
  35721. *
  35722. * const loader = new THREE.AudioLoader();
  35723. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35724. *
  35725. * ambientSound.setBuffer( audioBuffer );
  35726. * ambientSound.play();
  35727. * ```
  35728. *
  35729. * @augments Loader
  35730. */
  35731. class AudioLoader extends Loader {
  35732. /**
  35733. * Constructs a new audio loader.
  35734. *
  35735. * @param {LoadingManager} [manager] - The loading manager.
  35736. */
  35737. constructor( manager ) {
  35738. super( manager );
  35739. }
  35740. /**
  35741. * Starts loading from the given URL and passes the loaded audio buffer
  35742. * to the `onLoad()` callback.
  35743. *
  35744. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35745. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35746. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35747. * @param {onErrorCallback} onError - Executed when errors occur.
  35748. */
  35749. load( url, onLoad, onProgress, onError ) {
  35750. const scope = this;
  35751. const loader = new FileLoader( this.manager );
  35752. loader.setResponseType( 'arraybuffer' );
  35753. loader.setPath( this.path );
  35754. loader.setRequestHeader( this.requestHeader );
  35755. loader.setWithCredentials( this.withCredentials );
  35756. loader.load( url, function ( buffer ) {
  35757. try {
  35758. // Create a copy of the buffer. The `decodeAudioData` method
  35759. // detaches the buffer when complete, preventing reuse.
  35760. const bufferCopy = buffer.slice( 0 );
  35761. const context = AudioContext.getContext();
  35762. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35763. onLoad( audioBuffer );
  35764. } ).catch( handleError );
  35765. } catch ( e ) {
  35766. handleError( e );
  35767. }
  35768. }, onProgress, onError );
  35769. function handleError( e ) {
  35770. if ( onError ) {
  35771. onError( e );
  35772. } else {
  35773. console.error( e );
  35774. }
  35775. scope.manager.itemError( url );
  35776. }
  35777. }
  35778. }
  35779. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35780. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35781. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35782. /**
  35783. * A special type of camera that uses two perspective cameras with
  35784. * stereoscopic projection. Can be used for rendering stereo effects
  35785. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  35786. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  35787. */
  35788. class StereoCamera {
  35789. /**
  35790. * Constructs a new stereo camera.
  35791. */
  35792. constructor() {
  35793. /**
  35794. * The type property is used for detecting the object type
  35795. * in context of serialization/deserialization.
  35796. *
  35797. * @type {string}
  35798. * @readonly
  35799. */
  35800. this.type = 'StereoCamera';
  35801. /**
  35802. * The aspect.
  35803. *
  35804. * @type {number}
  35805. * @default 1
  35806. */
  35807. this.aspect = 1;
  35808. /**
  35809. * The eye separation which represents the distance
  35810. * between the left and right camera.
  35811. *
  35812. * @type {number}
  35813. * @default 0.064
  35814. */
  35815. this.eyeSep = 0.064;
  35816. /**
  35817. * The camera representing the left eye. This is added to layer `1` so objects to be
  35818. * rendered by the left camera must also be added to this layer.
  35819. *
  35820. * @type {PerspectiveCamera}
  35821. */
  35822. this.cameraL = new PerspectiveCamera();
  35823. this.cameraL.layers.enable( 1 );
  35824. this.cameraL.matrixAutoUpdate = false;
  35825. /**
  35826. * The camera representing the right eye. This is added to layer `2` so objects to be
  35827. * rendered by the right camera must also be added to this layer.
  35828. *
  35829. * @type {PerspectiveCamera}
  35830. */
  35831. this.cameraR = new PerspectiveCamera();
  35832. this.cameraR.layers.enable( 2 );
  35833. this.cameraR.matrixAutoUpdate = false;
  35834. this._cache = {
  35835. focus: null,
  35836. fov: null,
  35837. aspect: null,
  35838. near: null,
  35839. far: null,
  35840. zoom: null,
  35841. eyeSep: null
  35842. };
  35843. }
  35844. /**
  35845. * Updates the stereo camera based on the given perspective camera.
  35846. *
  35847. * @param {PerspectiveCamera} camera - The perspective camera.
  35848. */
  35849. update( camera ) {
  35850. const cache = this._cache;
  35851. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  35852. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  35853. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  35854. if ( needsUpdate ) {
  35855. cache.focus = camera.focus;
  35856. cache.fov = camera.fov;
  35857. cache.aspect = camera.aspect * this.aspect;
  35858. cache.near = camera.near;
  35859. cache.far = camera.far;
  35860. cache.zoom = camera.zoom;
  35861. cache.eyeSep = this.eyeSep;
  35862. // Off-axis stereoscopic effect based on
  35863. // http://paulbourke.net/stereographics/stereorender/
  35864. _projectionMatrix.copy( camera.projectionMatrix );
  35865. const eyeSepHalf = cache.eyeSep / 2;
  35866. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  35867. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  35868. let xmin, xmax;
  35869. // translate xOffset
  35870. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  35871. _eyeRight.elements[ 12 ] = eyeSepHalf;
  35872. // for left eye
  35873. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  35874. xmax = ymax * cache.aspect + eyeSepOnProjection;
  35875. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35876. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35877. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  35878. // for right eye
  35879. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  35880. xmax = ymax * cache.aspect - eyeSepOnProjection;
  35881. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35882. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35883. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  35884. }
  35885. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  35886. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  35887. }
  35888. }
  35889. /**
  35890. * This type of camera can be used in order to efficiently render a scene with a
  35891. * predefined set of cameras. This is an important performance aspect for
  35892. * rendering VR scenes.
  35893. *
  35894. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  35895. * to define for each sub camera the `viewport` property which determines the
  35896. * part of the viewport that is rendered with this camera.
  35897. *
  35898. * @augments PerspectiveCamera
  35899. */
  35900. class ArrayCamera extends PerspectiveCamera {
  35901. /**
  35902. * Constructs a new array camera.
  35903. *
  35904. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  35905. */
  35906. constructor( array = [] ) {
  35907. super();
  35908. /**
  35909. * This flag can be used for type testing.
  35910. *
  35911. * @type {boolean}
  35912. * @readonly
  35913. * @default true
  35914. */
  35915. this.isArrayCamera = true;
  35916. /**
  35917. * Whether this camera is used with multiview rendering or not.
  35918. *
  35919. * @type {boolean}
  35920. * @readonly
  35921. * @default false
  35922. */
  35923. this.isMultiViewCamera = false;
  35924. /**
  35925. * An array of perspective sub cameras.
  35926. *
  35927. * @type {Array<PerspectiveCamera>}
  35928. */
  35929. this.cameras = array;
  35930. }
  35931. }
  35932. /**
  35933. * Class for keeping track of time.
  35934. */
  35935. class Clock {
  35936. /**
  35937. * Constructs a new clock.
  35938. *
  35939. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  35940. * `getDelta()` is called for the first time.
  35941. */
  35942. constructor( autoStart = true ) {
  35943. /**
  35944. * If set to `true`, the clock starts automatically when `getDelta()` is called
  35945. * for the first time.
  35946. *
  35947. * @type {boolean}
  35948. * @default true
  35949. */
  35950. this.autoStart = autoStart;
  35951. /**
  35952. * Holds the time at which the clock's `start()` method was last called.
  35953. *
  35954. * @type {number}
  35955. * @default 0
  35956. */
  35957. this.startTime = 0;
  35958. /**
  35959. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  35960. * `getDelta()` methods were last called.
  35961. *
  35962. * @type {number}
  35963. * @default 0
  35964. */
  35965. this.oldTime = 0;
  35966. /**
  35967. * Keeps track of the total time that the clock has been running.
  35968. *
  35969. * @type {number}
  35970. * @default 0
  35971. */
  35972. this.elapsedTime = 0;
  35973. /**
  35974. * Whether the clock is running or not.
  35975. *
  35976. * @type {boolean}
  35977. * @default true
  35978. */
  35979. this.running = false;
  35980. }
  35981. /**
  35982. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  35983. * called by the class.
  35984. */
  35985. start() {
  35986. this.startTime = performance.now();
  35987. this.oldTime = this.startTime;
  35988. this.elapsedTime = 0;
  35989. this.running = true;
  35990. }
  35991. /**
  35992. * Stops the clock.
  35993. */
  35994. stop() {
  35995. this.getElapsedTime();
  35996. this.running = false;
  35997. this.autoStart = false;
  35998. }
  35999. /**
  36000. * Returns the elapsed time in seconds.
  36001. *
  36002. * @return {number} The elapsed time.
  36003. */
  36004. getElapsedTime() {
  36005. this.getDelta();
  36006. return this.elapsedTime;
  36007. }
  36008. /**
  36009. * Returns the delta time in seconds.
  36010. *
  36011. * @return {number} The delta time.
  36012. */
  36013. getDelta() {
  36014. let diff = 0;
  36015. if ( this.autoStart && ! this.running ) {
  36016. this.start();
  36017. return 0;
  36018. }
  36019. if ( this.running ) {
  36020. const newTime = performance.now();
  36021. diff = ( newTime - this.oldTime ) / 1000;
  36022. this.oldTime = newTime;
  36023. this.elapsedTime += diff;
  36024. }
  36025. return diff;
  36026. }
  36027. }
  36028. const _position$1 = /*@__PURE__*/ new Vector3();
  36029. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36030. const _scale$1 = /*@__PURE__*/ new Vector3();
  36031. const _forward = /*@__PURE__*/ new Vector3();
  36032. const _up = /*@__PURE__*/ new Vector3();
  36033. /**
  36034. * The class represents a virtual listener of the all positional and non-positional audio effects
  36035. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36036. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36037. *
  36038. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36039. * camera represents the 3D transformation of the listener.
  36040. *
  36041. * @augments Object3D
  36042. */
  36043. class AudioListener extends Object3D {
  36044. /**
  36045. * Constructs a new audio listener.
  36046. */
  36047. constructor() {
  36048. super();
  36049. this.type = 'AudioListener';
  36050. /**
  36051. * The native audio context.
  36052. *
  36053. * @type {AudioContext}
  36054. * @readonly
  36055. */
  36056. this.context = AudioContext.getContext();
  36057. /**
  36058. * The gain node used for volume control.
  36059. *
  36060. * @type {GainNode}
  36061. * @readonly
  36062. */
  36063. this.gain = this.context.createGain();
  36064. this.gain.connect( this.context.destination );
  36065. /**
  36066. * An optional filter.
  36067. *
  36068. * Defined via {@link AudioListener#setFilter}.
  36069. *
  36070. * @type {?AudioNode}
  36071. * @default null
  36072. * @readonly
  36073. */
  36074. this.filter = null;
  36075. /**
  36076. * Time delta values required for `linearRampToValueAtTime()` usage.
  36077. *
  36078. * @type {number}
  36079. * @default 0
  36080. * @readonly
  36081. */
  36082. this.timeDelta = 0;
  36083. // private
  36084. this._clock = new Clock();
  36085. }
  36086. /**
  36087. * Returns the listener's input node.
  36088. *
  36089. * This method is used by other audio nodes to connect to this listener.
  36090. *
  36091. * @return {GainNode} The input node.
  36092. */
  36093. getInput() {
  36094. return this.gain;
  36095. }
  36096. /**
  36097. * Removes the current filter from this listener.
  36098. *
  36099. * @return {AudioListener} A reference to this listener.
  36100. */
  36101. removeFilter() {
  36102. if ( this.filter !== null ) {
  36103. this.gain.disconnect( this.filter );
  36104. this.filter.disconnect( this.context.destination );
  36105. this.gain.connect( this.context.destination );
  36106. this.filter = null;
  36107. }
  36108. return this;
  36109. }
  36110. /**
  36111. * Returns the current set filter.
  36112. *
  36113. * @return {?AudioNode} The filter.
  36114. */
  36115. getFilter() {
  36116. return this.filter;
  36117. }
  36118. /**
  36119. * Sets the given filter to this listener.
  36120. *
  36121. * @param {AudioNode} value - The filter to set.
  36122. * @return {AudioListener} A reference to this listener.
  36123. */
  36124. setFilter( value ) {
  36125. if ( this.filter !== null ) {
  36126. this.gain.disconnect( this.filter );
  36127. this.filter.disconnect( this.context.destination );
  36128. } else {
  36129. this.gain.disconnect( this.context.destination );
  36130. }
  36131. this.filter = value;
  36132. this.gain.connect( this.filter );
  36133. this.filter.connect( this.context.destination );
  36134. return this;
  36135. }
  36136. /**
  36137. * Returns the applications master volume.
  36138. *
  36139. * @return {number} The master volume.
  36140. */
  36141. getMasterVolume() {
  36142. return this.gain.gain.value;
  36143. }
  36144. /**
  36145. * Sets the applications master volume. This volume setting affects
  36146. * all audio nodes in the scene.
  36147. *
  36148. * @param {number} value - The master volume to set.
  36149. * @return {AudioListener} A reference to this listener.
  36150. */
  36151. setMasterVolume( value ) {
  36152. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36153. return this;
  36154. }
  36155. updateMatrixWorld( force ) {
  36156. super.updateMatrixWorld( force );
  36157. const listener = this.context.listener;
  36158. this.timeDelta = this._clock.getDelta();
  36159. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36160. // the initial forward and up directions must be orthogonal
  36161. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36162. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36163. if ( listener.positionX ) {
  36164. // code path for Chrome (see #14393)
  36165. const endTime = this.context.currentTime + this.timeDelta;
  36166. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36167. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36168. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36169. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36170. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36171. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36172. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36173. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36174. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36175. } else {
  36176. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36177. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36178. }
  36179. }
  36180. }
  36181. /**
  36182. * Represents a non-positional ( global ) audio object.
  36183. *
  36184. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  36185. *
  36186. * ```js
  36187. * // create an AudioListener and add it to the camera
  36188. * const listener = new THREE.AudioListener();
  36189. * camera.add( listener );
  36190. *
  36191. * // create a global audio source
  36192. * const sound = new THREE.Audio( listener );
  36193. *
  36194. * // load a sound and set it as the Audio object's buffer
  36195. * const audioLoader = new THREE.AudioLoader();
  36196. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36197. * sound.setBuffer( buffer );
  36198. * sound.setLoop( true );
  36199. * sound.setVolume( 0.5 );
  36200. * sound.play();
  36201. * });
  36202. * ```
  36203. *
  36204. * @augments Object3D
  36205. */
  36206. class Audio extends Object3D {
  36207. /**
  36208. * Constructs a new audio.
  36209. *
  36210. * @param {AudioListener} listener - The global audio listener.
  36211. */
  36212. constructor( listener ) {
  36213. super();
  36214. this.type = 'Audio';
  36215. /**
  36216. * The global audio listener.
  36217. *
  36218. * @type {AudioListener}
  36219. * @readonly
  36220. */
  36221. this.listener = listener;
  36222. /**
  36223. * The audio context.
  36224. *
  36225. * @type {AudioContext}
  36226. * @readonly
  36227. */
  36228. this.context = listener.context;
  36229. /**
  36230. * The gain node used for volume control.
  36231. *
  36232. * @type {GainNode}
  36233. * @readonly
  36234. */
  36235. this.gain = this.context.createGain();
  36236. this.gain.connect( listener.getInput() );
  36237. /**
  36238. * Whether to start playback automatically or not.
  36239. *
  36240. * @type {boolean}
  36241. * @default false
  36242. */
  36243. this.autoplay = false;
  36244. /**
  36245. * A reference to an audio buffer.
  36246. *
  36247. * Defined via {@link Audio#setBuffer}.
  36248. *
  36249. * @type {?AudioBuffer}
  36250. * @default null
  36251. * @readonly
  36252. */
  36253. this.buffer = null;
  36254. /**
  36255. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36256. * +/- 1200 is an octave.
  36257. *
  36258. * Defined via {@link Audio#setDetune}.
  36259. *
  36260. * @type {number}
  36261. * @default 0
  36262. * @readonly
  36263. */
  36264. this.detune = 0;
  36265. /**
  36266. * Whether the audio should loop or not.
  36267. *
  36268. * Defined via {@link Audio#setLoop}.
  36269. *
  36270. * @type {boolean}
  36271. * @default false
  36272. * @readonly
  36273. */
  36274. this.loop = false;
  36275. /**
  36276. * Defines where in the audio buffer the replay should
  36277. * start, in seconds.
  36278. *
  36279. * @type {number}
  36280. * @default 0
  36281. */
  36282. this.loopStart = 0;
  36283. /**
  36284. * Defines where in the audio buffer the replay should
  36285. * stop, in seconds.
  36286. *
  36287. * @type {number}
  36288. * @default 0
  36289. */
  36290. this.loopEnd = 0;
  36291. /**
  36292. * An offset to the time within the audio buffer the playback
  36293. * should begin, in seconds.
  36294. *
  36295. * @type {number}
  36296. * @default 0
  36297. */
  36298. this.offset = 0;
  36299. /**
  36300. * Overrides the default duration of the audio.
  36301. *
  36302. * @type {undefined|number}
  36303. * @default undefined
  36304. */
  36305. this.duration = undefined;
  36306. /**
  36307. * The playback speed.
  36308. *
  36309. * Defined via {@link Audio#setPlaybackRate}.
  36310. *
  36311. * @type {number}
  36312. * @readonly
  36313. * @default 1
  36314. */
  36315. this.playbackRate = 1;
  36316. /**
  36317. * Indicates whether the audio is playing or not.
  36318. *
  36319. * This flag will be automatically set when using {@link Audio#play},
  36320. * {@link Audio#pause}, {@link Audio#stop}.
  36321. *
  36322. * @type {boolean}
  36323. * @readonly
  36324. * @default false
  36325. */
  36326. this.isPlaying = false;
  36327. /**
  36328. * Indicates whether the audio playback can be controlled
  36329. * with method like {@link Audio#play} or {@link Audio#pause}.
  36330. *
  36331. * This flag will be automatically set when audio sources are
  36332. * defined.
  36333. *
  36334. * @type {boolean}
  36335. * @readonly
  36336. * @default true
  36337. */
  36338. this.hasPlaybackControl = true;
  36339. /**
  36340. * Holds a reference to the current audio source.
  36341. *
  36342. * The property is automatically by one of the `set*()` methods.
  36343. *
  36344. * @type {?AudioNode}
  36345. * @readonly
  36346. * @default null
  36347. */
  36348. this.source = null;
  36349. /**
  36350. * Defines the source type.
  36351. *
  36352. * The property is automatically by one of the `set*()` methods.
  36353. *
  36354. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36355. * @readonly
  36356. * @default 'empty'
  36357. */
  36358. this.sourceType = 'empty';
  36359. this._startedAt = 0;
  36360. this._progress = 0;
  36361. this._connected = false;
  36362. /**
  36363. * Can be used to apply a variety of low-order filters to create
  36364. * more complex sound effects e.g. via `BiquadFilterNode`.
  36365. *
  36366. * The property is automatically set by {@link Audio#setFilters}.
  36367. *
  36368. * @type {Array<AudioNode>}
  36369. * @readonly
  36370. */
  36371. this.filters = [];
  36372. }
  36373. /**
  36374. * Returns the output audio node.
  36375. *
  36376. * @return {GainNode} The output node.
  36377. */
  36378. getOutput() {
  36379. return this.gain;
  36380. }
  36381. /**
  36382. * Sets the given audio node as the source of this instance.
  36383. *
  36384. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36385. *
  36386. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36387. * @return {Audio} A reference to this instance.
  36388. */
  36389. setNodeSource( audioNode ) {
  36390. this.hasPlaybackControl = false;
  36391. this.sourceType = 'audioNode';
  36392. this.source = audioNode;
  36393. this.connect();
  36394. return this;
  36395. }
  36396. /**
  36397. * Sets the given media element as the source of this instance.
  36398. *
  36399. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36400. *
  36401. * @param {HTMLMediaElement} mediaElement - The media element.
  36402. * @return {Audio} A reference to this instance.
  36403. */
  36404. setMediaElementSource( mediaElement ) {
  36405. this.hasPlaybackControl = false;
  36406. this.sourceType = 'mediaNode';
  36407. this.source = this.context.createMediaElementSource( mediaElement );
  36408. this.connect();
  36409. return this;
  36410. }
  36411. /**
  36412. * Sets the given media stream as the source of this instance.
  36413. *
  36414. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36415. *
  36416. * @param {MediaStream} mediaStream - The media stream.
  36417. * @return {Audio} A reference to this instance.
  36418. */
  36419. setMediaStreamSource( mediaStream ) {
  36420. this.hasPlaybackControl = false;
  36421. this.sourceType = 'mediaStreamNode';
  36422. this.source = this.context.createMediaStreamSource( mediaStream );
  36423. this.connect();
  36424. return this;
  36425. }
  36426. /**
  36427. * Sets the given audio buffer as the source of this instance.
  36428. *
  36429. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36430. *
  36431. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36432. * @return {Audio} A reference to this instance.
  36433. */
  36434. setBuffer( audioBuffer ) {
  36435. this.buffer = audioBuffer;
  36436. this.sourceType = 'buffer';
  36437. if ( this.autoplay ) this.play();
  36438. return this;
  36439. }
  36440. /**
  36441. * Starts the playback of the audio.
  36442. *
  36443. * Can only be used with compatible audio sources that allow playback control.
  36444. *
  36445. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36446. * @return {Audio|undefined} A reference to this instance.
  36447. */
  36448. play( delay = 0 ) {
  36449. if ( this.isPlaying === true ) {
  36450. console.warn( 'THREE.Audio: Audio is already playing.' );
  36451. return;
  36452. }
  36453. if ( this.hasPlaybackControl === false ) {
  36454. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36455. return;
  36456. }
  36457. this._startedAt = this.context.currentTime + delay;
  36458. const source = this.context.createBufferSource();
  36459. source.buffer = this.buffer;
  36460. source.loop = this.loop;
  36461. source.loopStart = this.loopStart;
  36462. source.loopEnd = this.loopEnd;
  36463. source.onended = this.onEnded.bind( this );
  36464. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36465. this.isPlaying = true;
  36466. this.source = source;
  36467. this.setDetune( this.detune );
  36468. this.setPlaybackRate( this.playbackRate );
  36469. return this.connect();
  36470. }
  36471. /**
  36472. * Pauses the playback of the audio.
  36473. *
  36474. * Can only be used with compatible audio sources that allow playback control.
  36475. *
  36476. * @return {Audio|undefined} A reference to this instance.
  36477. */
  36478. pause() {
  36479. if ( this.hasPlaybackControl === false ) {
  36480. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36481. return;
  36482. }
  36483. if ( this.isPlaying === true ) {
  36484. // update current progress
  36485. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36486. if ( this.loop === true ) {
  36487. // ensure _progress does not exceed duration with looped audios
  36488. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36489. }
  36490. this.source.stop();
  36491. this.source.onended = null;
  36492. this.isPlaying = false;
  36493. }
  36494. return this;
  36495. }
  36496. /**
  36497. * Stops the playback of the audio.
  36498. *
  36499. * Can only be used with compatible audio sources that allow playback control.
  36500. *
  36501. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36502. * @return {Audio|undefined} A reference to this instance.
  36503. */
  36504. stop( delay = 0 ) {
  36505. if ( this.hasPlaybackControl === false ) {
  36506. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36507. return;
  36508. }
  36509. this._progress = 0;
  36510. if ( this.source !== null ) {
  36511. this.source.stop( this.context.currentTime + delay );
  36512. this.source.onended = null;
  36513. }
  36514. this.isPlaying = false;
  36515. return this;
  36516. }
  36517. /**
  36518. * Connects to the audio source. This is used internally on
  36519. * initialisation and when setting / removing filters.
  36520. *
  36521. * @return {Audio} A reference to this instance.
  36522. */
  36523. connect() {
  36524. if ( this.filters.length > 0 ) {
  36525. this.source.connect( this.filters[ 0 ] );
  36526. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36527. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36528. }
  36529. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36530. } else {
  36531. this.source.connect( this.getOutput() );
  36532. }
  36533. this._connected = true;
  36534. return this;
  36535. }
  36536. /**
  36537. * Disconnects to the audio source. This is used internally on
  36538. * initialisation and when setting / removing filters.
  36539. *
  36540. * @return {Audio|undefined} A reference to this instance.
  36541. */
  36542. disconnect() {
  36543. if ( this._connected === false ) {
  36544. return;
  36545. }
  36546. if ( this.filters.length > 0 ) {
  36547. this.source.disconnect( this.filters[ 0 ] );
  36548. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36549. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36550. }
  36551. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36552. } else {
  36553. this.source.disconnect( this.getOutput() );
  36554. }
  36555. this._connected = false;
  36556. return this;
  36557. }
  36558. /**
  36559. * Returns the current set filters.
  36560. *
  36561. * @return {Array<AudioNode>} The list of filters.
  36562. */
  36563. getFilters() {
  36564. return this.filters;
  36565. }
  36566. /**
  36567. * Sets an array of filters and connects them with the audio source.
  36568. *
  36569. * @param {Array<AudioNode>} [value] - A list of filters.
  36570. * @return {Audio} A reference to this instance.
  36571. */
  36572. setFilters( value ) {
  36573. if ( ! value ) value = [];
  36574. if ( this._connected === true ) {
  36575. this.disconnect();
  36576. this.filters = value.slice();
  36577. this.connect();
  36578. } else {
  36579. this.filters = value.slice();
  36580. }
  36581. return this;
  36582. }
  36583. /**
  36584. * Defines the detuning of oscillation in cents.
  36585. *
  36586. * @param {number} value - The detuning of oscillation in cents.
  36587. * @return {Audio} A reference to this instance.
  36588. */
  36589. setDetune( value ) {
  36590. this.detune = value;
  36591. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36592. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36593. }
  36594. return this;
  36595. }
  36596. /**
  36597. * Returns the detuning of oscillation in cents.
  36598. *
  36599. * @return {number} The detuning of oscillation in cents.
  36600. */
  36601. getDetune() {
  36602. return this.detune;
  36603. }
  36604. /**
  36605. * Returns the first filter in the list of filters.
  36606. *
  36607. * @return {AudioNode|undefined} The first filter in the list of filters.
  36608. */
  36609. getFilter() {
  36610. return this.getFilters()[ 0 ];
  36611. }
  36612. /**
  36613. * Applies a single filter node to the audio.
  36614. *
  36615. * @param {AudioNode} [filter] - The filter to set.
  36616. * @return {Audio} A reference to this instance.
  36617. */
  36618. setFilter( filter ) {
  36619. return this.setFilters( filter ? [ filter ] : [] );
  36620. }
  36621. /**
  36622. * Sets the playback rate.
  36623. *
  36624. * Can only be used with compatible audio sources that allow playback control.
  36625. *
  36626. * @param {number} [value] - The playback rate to set.
  36627. * @return {Audio|undefined} A reference to this instance.
  36628. */
  36629. setPlaybackRate( value ) {
  36630. if ( this.hasPlaybackControl === false ) {
  36631. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36632. return;
  36633. }
  36634. this.playbackRate = value;
  36635. if ( this.isPlaying === true ) {
  36636. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36637. }
  36638. return this;
  36639. }
  36640. /**
  36641. * Returns the current playback rate.
  36642. * @return {number} The playback rate.
  36643. */
  36644. getPlaybackRate() {
  36645. return this.playbackRate;
  36646. }
  36647. /**
  36648. * Automatically called when playback finished.
  36649. */
  36650. onEnded() {
  36651. this.isPlaying = false;
  36652. this._progress = 0;
  36653. }
  36654. /**
  36655. * Returns the loop flag.
  36656. *
  36657. * Can only be used with compatible audio sources that allow playback control.
  36658. *
  36659. * @return {boolean} Whether the audio should loop or not.
  36660. */
  36661. getLoop() {
  36662. if ( this.hasPlaybackControl === false ) {
  36663. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36664. return false;
  36665. }
  36666. return this.loop;
  36667. }
  36668. /**
  36669. * Sets the loop flag.
  36670. *
  36671. * Can only be used with compatible audio sources that allow playback control.
  36672. *
  36673. * @param {boolean} value - Whether the audio should loop or not.
  36674. * @return {Audio|undefined} A reference to this instance.
  36675. */
  36676. setLoop( value ) {
  36677. if ( this.hasPlaybackControl === false ) {
  36678. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36679. return;
  36680. }
  36681. this.loop = value;
  36682. if ( this.isPlaying === true ) {
  36683. this.source.loop = this.loop;
  36684. }
  36685. return this;
  36686. }
  36687. /**
  36688. * Sets the loop start value which defines where in the audio buffer the replay should
  36689. * start, in seconds.
  36690. *
  36691. * @param {number} value - The loop start value.
  36692. * @return {Audio} A reference to this instance.
  36693. */
  36694. setLoopStart( value ) {
  36695. this.loopStart = value;
  36696. return this;
  36697. }
  36698. /**
  36699. * Sets the loop end value which defines where in the audio buffer the replay should
  36700. * stop, in seconds.
  36701. *
  36702. * @param {number} value - The loop end value.
  36703. * @return {Audio} A reference to this instance.
  36704. */
  36705. setLoopEnd( value ) {
  36706. this.loopEnd = value;
  36707. return this;
  36708. }
  36709. /**
  36710. * Returns the volume.
  36711. *
  36712. * @return {number} The volume.
  36713. */
  36714. getVolume() {
  36715. return this.gain.gain.value;
  36716. }
  36717. /**
  36718. * Sets the volume.
  36719. *
  36720. * @param {number} value - The volume to set.
  36721. * @return {Audio} A reference to this instance.
  36722. */
  36723. setVolume( value ) {
  36724. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36725. return this;
  36726. }
  36727. copy( source, recursive ) {
  36728. super.copy( source, recursive );
  36729. if ( source.sourceType !== 'buffer' ) {
  36730. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  36731. return this;
  36732. }
  36733. this.autoplay = source.autoplay;
  36734. this.buffer = source.buffer;
  36735. this.detune = source.detune;
  36736. this.loop = source.loop;
  36737. this.loopStart = source.loopStart;
  36738. this.loopEnd = source.loopEnd;
  36739. this.offset = source.offset;
  36740. this.duration = source.duration;
  36741. this.playbackRate = source.playbackRate;
  36742. this.hasPlaybackControl = source.hasPlaybackControl;
  36743. this.sourceType = source.sourceType;
  36744. this.filters = source.filters.slice();
  36745. return this;
  36746. }
  36747. clone( recursive ) {
  36748. return new this.constructor( this.listener ).copy( this, recursive );
  36749. }
  36750. }
  36751. const _position = /*@__PURE__*/ new Vector3();
  36752. const _quaternion = /*@__PURE__*/ new Quaternion();
  36753. const _scale = /*@__PURE__*/ new Vector3();
  36754. const _orientation = /*@__PURE__*/ new Vector3();
  36755. /**
  36756. * Represents a positional audio object.
  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 the PositionalAudio object (passing in the listener)
  36764. * const sound = new THREE.PositionalAudio( listener );
  36765. *
  36766. * // load a sound and set it as the PositionalAudio object's buffer
  36767. * const audioLoader = new THREE.AudioLoader();
  36768. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36769. * sound.setBuffer( buffer );
  36770. * sound.setRefDistance( 20 );
  36771. * sound.play();
  36772. * });
  36773. *
  36774. * // create an object for the sound to play from
  36775. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36776. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36777. * const mesh = new THREE.Mesh( sphere, material );
  36778. * scene.add( mesh );
  36779. *
  36780. * // finally add the sound to the mesh
  36781. * mesh.add( sound );
  36782. *
  36783. * @augments Audio
  36784. */
  36785. class PositionalAudio extends Audio {
  36786. /**
  36787. * Constructs a positional audio.
  36788. *
  36789. * @param {AudioListener} listener - The global audio listener.
  36790. */
  36791. constructor( listener ) {
  36792. super( listener );
  36793. /**
  36794. * The panner node represents the location, direction, and behavior of an audio
  36795. * source in 3D space.
  36796. *
  36797. * @type {PannerNode}
  36798. * @readonly
  36799. */
  36800. this.panner = this.context.createPanner();
  36801. this.panner.panningModel = 'HRTF';
  36802. this.panner.connect( this.gain );
  36803. }
  36804. connect() {
  36805. super.connect();
  36806. this.panner.connect( this.gain );
  36807. return this;
  36808. }
  36809. disconnect() {
  36810. super.disconnect();
  36811. this.panner.disconnect( this.gain );
  36812. return this;
  36813. }
  36814. getOutput() {
  36815. return this.panner;
  36816. }
  36817. /**
  36818. * Returns the current reference distance.
  36819. *
  36820. * @return {number} The reference distance.
  36821. */
  36822. getRefDistance() {
  36823. return this.panner.refDistance;
  36824. }
  36825. /**
  36826. * Defines the reference distance for reducing volume as the audio source moves
  36827. * further from the listener – i.e. the distance at which the volume reduction
  36828. * starts taking effect.
  36829. *
  36830. * @param {number} value - The reference distance to set.
  36831. * @return {PositionalAudio} A reference to this instance.
  36832. */
  36833. setRefDistance( value ) {
  36834. this.panner.refDistance = value;
  36835. return this;
  36836. }
  36837. /**
  36838. * Returns the current rolloff factor.
  36839. *
  36840. * @return {number} The rolloff factor.
  36841. */
  36842. getRolloffFactor() {
  36843. return this.panner.rolloffFactor;
  36844. }
  36845. /**
  36846. * Defines how quickly the volume is reduced as the source moves away from the listener.
  36847. *
  36848. * @param {number} value - The rolloff factor.
  36849. * @return {PositionalAudio} A reference to this instance.
  36850. */
  36851. setRolloffFactor( value ) {
  36852. this.panner.rolloffFactor = value;
  36853. return this;
  36854. }
  36855. /**
  36856. * Returns the current distance model.
  36857. *
  36858. * @return {('linear'|'inverse'|'exponential')} The distance model.
  36859. */
  36860. getDistanceModel() {
  36861. return this.panner.distanceModel;
  36862. }
  36863. /**
  36864. * Defines which algorithm to use to reduce the volume of the audio source
  36865. * as it moves away from the listener.
  36866. *
  36867. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  36868. * for more details.
  36869. *
  36870. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  36871. * @return {PositionalAudio} A reference to this instance.
  36872. */
  36873. setDistanceModel( value ) {
  36874. this.panner.distanceModel = value;
  36875. return this;
  36876. }
  36877. /**
  36878. * Returns the current max distance.
  36879. *
  36880. * @return {number} The max distance.
  36881. */
  36882. getMaxDistance() {
  36883. return this.panner.maxDistance;
  36884. }
  36885. /**
  36886. * Defines the maximum distance between the audio source and the listener,
  36887. * after which the volume is not reduced any further.
  36888. *
  36889. * This value is used only by the `linear` distance model.
  36890. *
  36891. * @param {number} value - The max distance.
  36892. * @return {PositionalAudio} A reference to this instance.
  36893. */
  36894. setMaxDistance( value ) {
  36895. this.panner.maxDistance = value;
  36896. return this;
  36897. }
  36898. /**
  36899. * Sets the directional cone in which the audio can be listened.
  36900. *
  36901. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  36902. * @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.
  36903. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  36904. * @return {PositionalAudio} A reference to this instance.
  36905. */
  36906. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  36907. this.panner.coneInnerAngle = coneInnerAngle;
  36908. this.panner.coneOuterAngle = coneOuterAngle;
  36909. this.panner.coneOuterGain = coneOuterGain;
  36910. return this;
  36911. }
  36912. updateMatrixWorld( force ) {
  36913. super.updateMatrixWorld( force );
  36914. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  36915. this.matrixWorld.decompose( _position, _quaternion, _scale );
  36916. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  36917. const panner = this.panner;
  36918. if ( panner.positionX ) {
  36919. // code path for Chrome and Firefox (see #14393)
  36920. const endTime = this.context.currentTime + this.listener.timeDelta;
  36921. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  36922. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  36923. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  36924. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  36925. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  36926. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  36927. } else {
  36928. panner.setPosition( _position.x, _position.y, _position.z );
  36929. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  36930. }
  36931. }
  36932. }
  36933. /**
  36934. * This class can be used to analyse audio data.
  36935. *
  36936. * ```js
  36937. * // create an AudioListener and add it to the camera
  36938. * const listener = new THREE.AudioListener();
  36939. * camera.add( listener );
  36940. *
  36941. * // create an Audio source
  36942. * const sound = new THREE.Audio( listener );
  36943. *
  36944. * // load a sound and set it as the Audio object's buffer
  36945. * const audioLoader = new THREE.AudioLoader();
  36946. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36947. * sound.setBuffer( buffer );
  36948. * sound.setLoop(true);
  36949. * sound.setVolume(0.5);
  36950. * sound.play();
  36951. * });
  36952. *
  36953. * // create an AudioAnalyser, passing in the sound and desired fftSize
  36954. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  36955. *
  36956. * // get the average frequency of the sound
  36957. * const data = analyser.getAverageFrequency();
  36958. * ```
  36959. */
  36960. class AudioAnalyser {
  36961. /**
  36962. * Constructs a new audio analyzer.
  36963. *
  36964. * @param {Audio} audio - The audio to analyze.
  36965. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  36966. */
  36967. constructor( audio, fftSize = 2048 ) {
  36968. /**
  36969. * The global audio listener.
  36970. *
  36971. * @type {AnalyserNode}
  36972. */
  36973. this.analyser = audio.context.createAnalyser();
  36974. this.analyser.fftSize = fftSize;
  36975. /**
  36976. * Holds the analyzed data.
  36977. *
  36978. * @type {Uint8Array}
  36979. */
  36980. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  36981. audio.getOutput().connect( this.analyser );
  36982. }
  36983. /**
  36984. * Returns an array with frequency data of the audio.
  36985. *
  36986. * Each item in the array represents the decibel value for a specific frequency.
  36987. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  36988. * For example, for 48000 sample rate, the last item of the array will represent
  36989. * the decibel value for 24000 Hz.
  36990. *
  36991. * @return {Uint8Array} The frequency data.
  36992. */
  36993. getFrequencyData() {
  36994. this.analyser.getByteFrequencyData( this.data );
  36995. return this.data;
  36996. }
  36997. /**
  36998. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  36999. *
  37000. * @return {number} The average frequency.
  37001. */
  37002. getAverageFrequency() {
  37003. let value = 0;
  37004. const data = this.getFrequencyData();
  37005. for ( let i = 0; i < data.length; i ++ ) {
  37006. value += data[ i ];
  37007. }
  37008. return value / data.length;
  37009. }
  37010. }
  37011. /**
  37012. * Buffered scene graph property that allows weighted accumulation; used internally.
  37013. */
  37014. class PropertyMixer {
  37015. /**
  37016. * Constructs a new property mixer.
  37017. *
  37018. * @param {PropertyBinding} binding - The property binding.
  37019. * @param {string} typeName - The keyframe track type name.
  37020. * @param {number} valueSize - The keyframe track value size.
  37021. */
  37022. constructor( binding, typeName, valueSize ) {
  37023. /**
  37024. * The property binding.
  37025. *
  37026. * @type {PropertyBinding}
  37027. */
  37028. this.binding = binding;
  37029. /**
  37030. * The keyframe track value size.
  37031. *
  37032. * @type {number}
  37033. */
  37034. this.valueSize = valueSize;
  37035. let mixFunction,
  37036. mixFunctionAdditive,
  37037. setIdentity;
  37038. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37039. //
  37040. // interpolators can use .buffer as their .result
  37041. // the data then goes to 'incoming'
  37042. //
  37043. // 'accu0' and 'accu1' are used frame-interleaved for
  37044. // the cumulative result and are compared to detect
  37045. // changes
  37046. //
  37047. // 'orig' stores the original state of the property
  37048. //
  37049. // 'add' is used for additive cumulative results
  37050. //
  37051. // 'work' is optional and is only present for quaternion types. It is used
  37052. // to store intermediate quaternion multiplication results
  37053. switch ( typeName ) {
  37054. case 'quaternion':
  37055. mixFunction = this._slerp;
  37056. mixFunctionAdditive = this._slerpAdditive;
  37057. setIdentity = this._setAdditiveIdentityQuaternion;
  37058. this.buffer = new Float64Array( valueSize * 6 );
  37059. this._workIndex = 5;
  37060. break;
  37061. case 'string':
  37062. case 'bool':
  37063. mixFunction = this._select;
  37064. // Use the regular mix function and for additive on these types,
  37065. // additive is not relevant for non-numeric types
  37066. mixFunctionAdditive = this._select;
  37067. setIdentity = this._setAdditiveIdentityOther;
  37068. this.buffer = new Array( valueSize * 5 );
  37069. break;
  37070. default:
  37071. mixFunction = this._lerp;
  37072. mixFunctionAdditive = this._lerpAdditive;
  37073. setIdentity = this._setAdditiveIdentityNumeric;
  37074. this.buffer = new Float64Array( valueSize * 5 );
  37075. }
  37076. this._mixBufferRegion = mixFunction;
  37077. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37078. this._setIdentity = setIdentity;
  37079. this._origIndex = 3;
  37080. this._addIndex = 4;
  37081. /**
  37082. * TODO
  37083. *
  37084. * @type {number}
  37085. * @default 0
  37086. */
  37087. this.cumulativeWeight = 0;
  37088. /**
  37089. * TODO
  37090. *
  37091. * @type {number}
  37092. * @default 0
  37093. */
  37094. this.cumulativeWeightAdditive = 0;
  37095. /**
  37096. * TODO
  37097. *
  37098. * @type {number}
  37099. * @default 0
  37100. */
  37101. this.useCount = 0;
  37102. /**
  37103. * TODO
  37104. *
  37105. * @type {number}
  37106. * @default 0
  37107. */
  37108. this.referenceCount = 0;
  37109. }
  37110. /**
  37111. * Accumulates data in the `incoming` region into `accu<i>`.
  37112. *
  37113. * @param {number} accuIndex - The accumulation index.
  37114. * @param {number} weight - The weight.
  37115. */
  37116. accumulate( accuIndex, weight ) {
  37117. // note: happily accumulating nothing when weight = 0, the caller knows
  37118. // the weight and shouldn't have made the call in the first place
  37119. const buffer = this.buffer,
  37120. stride = this.valueSize,
  37121. offset = accuIndex * stride + stride;
  37122. let currentWeight = this.cumulativeWeight;
  37123. if ( currentWeight === 0 ) {
  37124. // accuN := incoming * weight
  37125. for ( let i = 0; i !== stride; ++ i ) {
  37126. buffer[ offset + i ] = buffer[ i ];
  37127. }
  37128. currentWeight = weight;
  37129. } else {
  37130. // accuN := accuN + incoming * weight
  37131. currentWeight += weight;
  37132. const mix = weight / currentWeight;
  37133. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37134. }
  37135. this.cumulativeWeight = currentWeight;
  37136. }
  37137. /**
  37138. * Accumulates data in the `incoming` region into `add`.
  37139. *
  37140. * @param {number} weight - The weight.
  37141. */
  37142. accumulateAdditive( weight ) {
  37143. const buffer = this.buffer,
  37144. stride = this.valueSize,
  37145. offset = stride * this._addIndex;
  37146. if ( this.cumulativeWeightAdditive === 0 ) {
  37147. // add = identity
  37148. this._setIdentity();
  37149. }
  37150. // add := add + incoming * weight
  37151. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37152. this.cumulativeWeightAdditive += weight;
  37153. }
  37154. /**
  37155. * Applies the state of `accu<i>` to the binding when accus differ.
  37156. *
  37157. * @param {number} accuIndex - The accumulation index.
  37158. */
  37159. apply( accuIndex ) {
  37160. const stride = this.valueSize,
  37161. buffer = this.buffer,
  37162. offset = accuIndex * stride + stride,
  37163. weight = this.cumulativeWeight,
  37164. weightAdditive = this.cumulativeWeightAdditive,
  37165. binding = this.binding;
  37166. this.cumulativeWeight = 0;
  37167. this.cumulativeWeightAdditive = 0;
  37168. if ( weight < 1 ) {
  37169. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37170. const originalValueOffset = stride * this._origIndex;
  37171. this._mixBufferRegion(
  37172. buffer, offset, originalValueOffset, 1 - weight, stride );
  37173. }
  37174. if ( weightAdditive > 0 ) {
  37175. // accuN := accuN + additive accuN
  37176. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37177. }
  37178. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37179. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37180. // value has changed -> update scene graph
  37181. binding.setValue( buffer, offset );
  37182. break;
  37183. }
  37184. }
  37185. }
  37186. /**
  37187. * Remembers the state of the bound property and copy it to both accus.
  37188. */
  37189. saveOriginalState() {
  37190. const binding = this.binding;
  37191. const buffer = this.buffer,
  37192. stride = this.valueSize,
  37193. originalValueOffset = stride * this._origIndex;
  37194. binding.getValue( buffer, originalValueOffset );
  37195. // accu[0..1] := orig -- initially detect changes against the original
  37196. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37197. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37198. }
  37199. // Add to identity for additive
  37200. this._setIdentity();
  37201. this.cumulativeWeight = 0;
  37202. this.cumulativeWeightAdditive = 0;
  37203. }
  37204. /**
  37205. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37206. */
  37207. restoreOriginalState() {
  37208. const originalValueOffset = this.valueSize * 3;
  37209. this.binding.setValue( this.buffer, originalValueOffset );
  37210. }
  37211. // internals
  37212. _setAdditiveIdentityNumeric() {
  37213. const startIndex = this._addIndex * this.valueSize;
  37214. const endIndex = startIndex + this.valueSize;
  37215. for ( let i = startIndex; i < endIndex; i ++ ) {
  37216. this.buffer[ i ] = 0;
  37217. }
  37218. }
  37219. _setAdditiveIdentityQuaternion() {
  37220. this._setAdditiveIdentityNumeric();
  37221. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37222. }
  37223. _setAdditiveIdentityOther() {
  37224. const startIndex = this._origIndex * this.valueSize;
  37225. const targetIndex = this._addIndex * this.valueSize;
  37226. for ( let i = 0; i < this.valueSize; i ++ ) {
  37227. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37228. }
  37229. }
  37230. // mix functions
  37231. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37232. if ( t >= 0.5 ) {
  37233. for ( let i = 0; i !== stride; ++ i ) {
  37234. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37235. }
  37236. }
  37237. }
  37238. _slerp( buffer, dstOffset, srcOffset, t ) {
  37239. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37240. }
  37241. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37242. const workOffset = this._workIndex * stride;
  37243. // Store result in intermediate buffer offset
  37244. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37245. // Slerp to the intermediate result
  37246. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37247. }
  37248. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37249. const s = 1 - t;
  37250. for ( let i = 0; i !== stride; ++ i ) {
  37251. const j = dstOffset + i;
  37252. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37253. }
  37254. }
  37255. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37256. for ( let i = 0; i !== stride; ++ i ) {
  37257. const j = dstOffset + i;
  37258. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37259. }
  37260. }
  37261. }
  37262. // Characters [].:/ are reserved for track binding syntax.
  37263. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37264. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37265. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37266. // only latin characters, and the unicode \p{L} is not yet supported. So
  37267. // instead, we exclude reserved characters and match everything else.
  37268. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37269. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37270. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37271. // be matched to parse the rest of the track name.
  37272. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37273. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37274. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37275. // Object on target node, and accessor. May not contain reserved
  37276. // characters. Accessor may contain any character except closing bracket.
  37277. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37278. // Property and accessor. May not contain reserved characters. Accessor may
  37279. // contain any non-bracket characters.
  37280. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37281. const _trackRe = new RegExp( ''
  37282. + '^'
  37283. + _directoryRe
  37284. + _nodeRe
  37285. + _objectRe
  37286. + _propertyRe
  37287. + '$'
  37288. );
  37289. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37290. class Composite {
  37291. constructor( targetGroup, path, optionalParsedPath ) {
  37292. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37293. this._targetGroup = targetGroup;
  37294. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37295. }
  37296. getValue( array, offset ) {
  37297. this.bind(); // bind all binding
  37298. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37299. binding = this._bindings[ firstValidIndex ];
  37300. // and only call .getValue on the first
  37301. if ( binding !== undefined ) binding.getValue( array, offset );
  37302. }
  37303. setValue( array, offset ) {
  37304. const bindings = this._bindings;
  37305. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37306. bindings[ i ].setValue( array, offset );
  37307. }
  37308. }
  37309. bind() {
  37310. const bindings = this._bindings;
  37311. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37312. bindings[ i ].bind();
  37313. }
  37314. }
  37315. unbind() {
  37316. const bindings = this._bindings;
  37317. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37318. bindings[ i ].unbind();
  37319. }
  37320. }
  37321. }
  37322. // Note: This class uses a State pattern on a per-method basis:
  37323. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37324. // prototype version of these methods with one that represents
  37325. // the bound state. When the property is not found, the methods
  37326. // become no-ops.
  37327. /**
  37328. * This holds a reference to a real property in the scene graph; used internally.
  37329. */
  37330. class PropertyBinding {
  37331. /**
  37332. * Constructs a new property binding.
  37333. *
  37334. * @param {Object} rootNode - The root node.
  37335. * @param {string} path - The path.
  37336. * @param {?Object} [parsedPath] - The parsed path.
  37337. */
  37338. constructor( rootNode, path, parsedPath ) {
  37339. /**
  37340. * The object path to the animated property.
  37341. *
  37342. * @type {string}
  37343. */
  37344. this.path = path;
  37345. /**
  37346. * An object holding information about the path.
  37347. *
  37348. * @type {Object}
  37349. */
  37350. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37351. /**
  37352. * The object owns the animated property.
  37353. *
  37354. * @type {?Object}
  37355. */
  37356. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37357. /**
  37358. * The root node.
  37359. *
  37360. * @type {Object3D|Skeleton}
  37361. */
  37362. this.rootNode = rootNode;
  37363. // initial state of these methods that calls 'bind'
  37364. this.getValue = this._getValue_unbound;
  37365. this.setValue = this._setValue_unbound;
  37366. }
  37367. /**
  37368. * Factory method for creating a property binding from the given parameters.
  37369. *
  37370. * @static
  37371. * @param {Object} root - The root node.
  37372. * @param {string} path - The path.
  37373. * @param {?Object} [parsedPath] - The parsed path.
  37374. * @return {PropertyBinding|Composite} The created property binding or composite.
  37375. */
  37376. static create( root, path, parsedPath ) {
  37377. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37378. return new PropertyBinding( root, path, parsedPath );
  37379. } else {
  37380. return new PropertyBinding.Composite( root, path, parsedPath );
  37381. }
  37382. }
  37383. /**
  37384. * Replaces spaces with underscores and removes unsupported characters from
  37385. * node names, to ensure compatibility with parseTrackName().
  37386. *
  37387. * @param {string} name - Node name to be sanitized.
  37388. * @return {string} The sanitized node name.
  37389. */
  37390. static sanitizeNodeName( name ) {
  37391. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37392. }
  37393. /**
  37394. * Parses the given track name (an object path to an animated property) and
  37395. * returns an object with information about the path. Matches strings in the following forms:
  37396. *
  37397. * - nodeName.property
  37398. * - nodeName.property[accessor]
  37399. * - nodeName.material.property[accessor]
  37400. * - uuid.property[accessor]
  37401. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37402. * - parentName/nodeName.property
  37403. * - parentName/parentName/nodeName.property[index]
  37404. * - .bone[Armature.DEF_cog].position
  37405. * - scene:helium_balloon_model:helium_balloon_model.position
  37406. *
  37407. * @static
  37408. * @param {string} trackName - The track name to parse.
  37409. * @return {Object} The parsed track name as an object.
  37410. */
  37411. static parseTrackName( trackName ) {
  37412. const matches = _trackRe.exec( trackName );
  37413. if ( matches === null ) {
  37414. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37415. }
  37416. const results = {
  37417. // directoryName: matches[ 1 ], // (tschw) currently unused
  37418. nodeName: matches[ 2 ],
  37419. objectName: matches[ 3 ],
  37420. objectIndex: matches[ 4 ],
  37421. propertyName: matches[ 5 ], // required
  37422. propertyIndex: matches[ 6 ]
  37423. };
  37424. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37425. if ( lastDot !== undefined && lastDot !== -1 ) {
  37426. const objectName = results.nodeName.substring( lastDot + 1 );
  37427. // Object names must be checked against an allowlist. Otherwise, there
  37428. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37429. // 'bar' could be the objectName, or part of a nodeName (which can
  37430. // include '.' characters).
  37431. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37432. results.nodeName = results.nodeName.substring( 0, lastDot );
  37433. results.objectName = objectName;
  37434. }
  37435. }
  37436. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37437. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37438. }
  37439. return results;
  37440. }
  37441. /**
  37442. * Searches for a node in the hierarchy of the given root object by the given
  37443. * node name.
  37444. *
  37445. * @static
  37446. * @param {Object} root - The root object.
  37447. * @param {string|number} nodeName - The name of the node.
  37448. * @return {?Object} The found node. Returns `null` if no object was found.
  37449. */
  37450. static findNode( root, nodeName ) {
  37451. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37452. return root;
  37453. }
  37454. // search into skeleton bones.
  37455. if ( root.skeleton ) {
  37456. const bone = root.skeleton.getBoneByName( nodeName );
  37457. if ( bone !== undefined ) {
  37458. return bone;
  37459. }
  37460. }
  37461. // search into node subtree.
  37462. if ( root.children ) {
  37463. const searchNodeSubtree = function ( children ) {
  37464. for ( let i = 0; i < children.length; i ++ ) {
  37465. const childNode = children[ i ];
  37466. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37467. return childNode;
  37468. }
  37469. const result = searchNodeSubtree( childNode.children );
  37470. if ( result ) return result;
  37471. }
  37472. return null;
  37473. };
  37474. const subTreeNode = searchNodeSubtree( root.children );
  37475. if ( subTreeNode ) {
  37476. return subTreeNode;
  37477. }
  37478. }
  37479. return null;
  37480. }
  37481. // these are used to "bind" a nonexistent property
  37482. _getValue_unavailable() {}
  37483. _setValue_unavailable() {}
  37484. // Getters
  37485. _getValue_direct( buffer, offset ) {
  37486. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37487. }
  37488. _getValue_array( buffer, offset ) {
  37489. const source = this.resolvedProperty;
  37490. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37491. buffer[ offset ++ ] = source[ i ];
  37492. }
  37493. }
  37494. _getValue_arrayElement( buffer, offset ) {
  37495. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37496. }
  37497. _getValue_toArray( buffer, offset ) {
  37498. this.resolvedProperty.toArray( buffer, offset );
  37499. }
  37500. // Direct
  37501. _setValue_direct( buffer, offset ) {
  37502. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37503. }
  37504. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37505. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37506. this.targetObject.needsUpdate = true;
  37507. }
  37508. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37509. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37510. this.targetObject.matrixWorldNeedsUpdate = true;
  37511. }
  37512. // EntireArray
  37513. _setValue_array( buffer, offset ) {
  37514. const dest = this.resolvedProperty;
  37515. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37516. dest[ i ] = buffer[ offset ++ ];
  37517. }
  37518. }
  37519. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37520. const dest = this.resolvedProperty;
  37521. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37522. dest[ i ] = buffer[ offset ++ ];
  37523. }
  37524. this.targetObject.needsUpdate = true;
  37525. }
  37526. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37527. const dest = this.resolvedProperty;
  37528. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37529. dest[ i ] = buffer[ offset ++ ];
  37530. }
  37531. this.targetObject.matrixWorldNeedsUpdate = true;
  37532. }
  37533. // ArrayElement
  37534. _setValue_arrayElement( buffer, offset ) {
  37535. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37536. }
  37537. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37538. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37539. this.targetObject.needsUpdate = true;
  37540. }
  37541. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37542. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37543. this.targetObject.matrixWorldNeedsUpdate = true;
  37544. }
  37545. // HasToFromArray
  37546. _setValue_fromArray( buffer, offset ) {
  37547. this.resolvedProperty.fromArray( buffer, offset );
  37548. }
  37549. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37550. this.resolvedProperty.fromArray( buffer, offset );
  37551. this.targetObject.needsUpdate = true;
  37552. }
  37553. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37554. this.resolvedProperty.fromArray( buffer, offset );
  37555. this.targetObject.matrixWorldNeedsUpdate = true;
  37556. }
  37557. _getValue_unbound( targetArray, offset ) {
  37558. this.bind();
  37559. this.getValue( targetArray, offset );
  37560. }
  37561. _setValue_unbound( sourceArray, offset ) {
  37562. this.bind();
  37563. this.setValue( sourceArray, offset );
  37564. }
  37565. /**
  37566. * Creates a getter / setter pair for the property tracked by this binding.
  37567. */
  37568. bind() {
  37569. let targetObject = this.node;
  37570. const parsedPath = this.parsedPath;
  37571. const objectName = parsedPath.objectName;
  37572. const propertyName = parsedPath.propertyName;
  37573. let propertyIndex = parsedPath.propertyIndex;
  37574. if ( ! targetObject ) {
  37575. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37576. this.node = targetObject;
  37577. }
  37578. // set fail state so we can just 'return' on error
  37579. this.getValue = this._getValue_unavailable;
  37580. this.setValue = this._setValue_unavailable;
  37581. // ensure there is a value node
  37582. if ( ! targetObject ) {
  37583. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  37584. return;
  37585. }
  37586. if ( objectName ) {
  37587. let objectIndex = parsedPath.objectIndex;
  37588. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37589. switch ( objectName ) {
  37590. case 'materials':
  37591. if ( ! targetObject.material ) {
  37592. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37593. return;
  37594. }
  37595. if ( ! targetObject.material.materials ) {
  37596. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37597. return;
  37598. }
  37599. targetObject = targetObject.material.materials;
  37600. break;
  37601. case 'bones':
  37602. if ( ! targetObject.skeleton ) {
  37603. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37604. return;
  37605. }
  37606. // potential future optimization: skip this if propertyIndex is already an integer
  37607. // and convert the integer string to a true integer.
  37608. targetObject = targetObject.skeleton.bones;
  37609. // support resolving morphTarget names into indices.
  37610. for ( let i = 0; i < targetObject.length; i ++ ) {
  37611. if ( targetObject[ i ].name === objectIndex ) {
  37612. objectIndex = i;
  37613. break;
  37614. }
  37615. }
  37616. break;
  37617. case 'map':
  37618. if ( 'map' in targetObject ) {
  37619. targetObject = targetObject.map;
  37620. break;
  37621. }
  37622. if ( ! targetObject.material ) {
  37623. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37624. return;
  37625. }
  37626. if ( ! targetObject.material.map ) {
  37627. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37628. return;
  37629. }
  37630. targetObject = targetObject.material.map;
  37631. break;
  37632. default:
  37633. if ( targetObject[ objectName ] === undefined ) {
  37634. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  37635. return;
  37636. }
  37637. targetObject = targetObject[ objectName ];
  37638. }
  37639. if ( objectIndex !== undefined ) {
  37640. if ( targetObject[ objectIndex ] === undefined ) {
  37641. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37642. return;
  37643. }
  37644. targetObject = targetObject[ objectIndex ];
  37645. }
  37646. }
  37647. // resolve property
  37648. const nodeProperty = targetObject[ propertyName ];
  37649. if ( nodeProperty === undefined ) {
  37650. const nodeName = parsedPath.nodeName;
  37651. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  37652. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37653. return;
  37654. }
  37655. // determine versioning scheme
  37656. let versioning = this.Versioning.None;
  37657. this.targetObject = targetObject;
  37658. if ( targetObject.isMaterial === true ) {
  37659. versioning = this.Versioning.NeedsUpdate;
  37660. } else if ( targetObject.isObject3D === true ) {
  37661. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37662. }
  37663. // determine how the property gets bound
  37664. let bindingType = this.BindingType.Direct;
  37665. if ( propertyIndex !== undefined ) {
  37666. // access a sub element of the property array (only primitives are supported right now)
  37667. if ( propertyName === 'morphTargetInfluences' ) {
  37668. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37669. // support resolving morphTarget names into indices.
  37670. if ( ! targetObject.geometry ) {
  37671. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37672. return;
  37673. }
  37674. if ( ! targetObject.geometry.morphAttributes ) {
  37675. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37676. return;
  37677. }
  37678. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37679. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37680. }
  37681. }
  37682. bindingType = this.BindingType.ArrayElement;
  37683. this.resolvedProperty = nodeProperty;
  37684. this.propertyIndex = propertyIndex;
  37685. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37686. // must use copy for Object3D.Euler/Quaternion
  37687. bindingType = this.BindingType.HasFromToArray;
  37688. this.resolvedProperty = nodeProperty;
  37689. } else if ( Array.isArray( nodeProperty ) ) {
  37690. bindingType = this.BindingType.EntireArray;
  37691. this.resolvedProperty = nodeProperty;
  37692. } else {
  37693. this.propertyName = propertyName;
  37694. }
  37695. // select getter / setter
  37696. this.getValue = this.GetterByBindingType[ bindingType ];
  37697. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37698. }
  37699. /**
  37700. * Unbinds the property.
  37701. */
  37702. unbind() {
  37703. this.node = null;
  37704. // back to the prototype version of getValue / setValue
  37705. // note: avoiding to mutate the shape of 'this' via 'delete'
  37706. this.getValue = this._getValue_unbound;
  37707. this.setValue = this._setValue_unbound;
  37708. }
  37709. }
  37710. PropertyBinding.Composite = Composite;
  37711. PropertyBinding.prototype.BindingType = {
  37712. Direct: 0,
  37713. EntireArray: 1,
  37714. ArrayElement: 2,
  37715. HasFromToArray: 3
  37716. };
  37717. PropertyBinding.prototype.Versioning = {
  37718. None: 0,
  37719. NeedsUpdate: 1,
  37720. MatrixWorldNeedsUpdate: 2
  37721. };
  37722. PropertyBinding.prototype.GetterByBindingType = [
  37723. PropertyBinding.prototype._getValue_direct,
  37724. PropertyBinding.prototype._getValue_array,
  37725. PropertyBinding.prototype._getValue_arrayElement,
  37726. PropertyBinding.prototype._getValue_toArray,
  37727. ];
  37728. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37729. [
  37730. // Direct
  37731. PropertyBinding.prototype._setValue_direct,
  37732. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37733. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37734. ], [
  37735. // EntireArray
  37736. PropertyBinding.prototype._setValue_array,
  37737. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37738. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37739. ], [
  37740. // ArrayElement
  37741. PropertyBinding.prototype._setValue_arrayElement,
  37742. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37743. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37744. ], [
  37745. // HasToFromArray
  37746. PropertyBinding.prototype._setValue_fromArray,
  37747. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37748. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37749. ]
  37750. ];
  37751. /**
  37752. * A group of objects that receives a shared animation state.
  37753. *
  37754. * Usage:
  37755. *
  37756. * - Add objects you would otherwise pass as 'root' to the
  37757. * constructor or the .clipAction method of AnimationMixer.
  37758. * - Instead pass this object as 'root'.
  37759. * - You can also add and remove objects later when the mixer is running.
  37760. *
  37761. * Note:
  37762. *
  37763. * - Objects of this class appear as one object to the mixer,
  37764. * so cache control of the individual objects must be done on the group.
  37765. *
  37766. * Limitation:
  37767. *
  37768. * - The animated properties must be compatible among the all objects in the group.
  37769. * - A single property can either be controlled through a target group or directly, but not both.
  37770. */
  37771. class AnimationObjectGroup {
  37772. /**
  37773. * Constructs a new animation group.
  37774. *
  37775. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37776. */
  37777. constructor() {
  37778. /**
  37779. * This flag can be used for type testing.
  37780. *
  37781. * @type {boolean}
  37782. * @readonly
  37783. * @default true
  37784. */
  37785. this.isAnimationObjectGroup = true;
  37786. /**
  37787. * The UUID of the 3D object.
  37788. *
  37789. * @type {string}
  37790. * @readonly
  37791. */
  37792. this.uuid = generateUUID();
  37793. // cached objects followed by the active ones
  37794. this._objects = Array.prototype.slice.call( arguments );
  37795. this.nCachedObjects_ = 0; // threshold
  37796. // note: read by PropertyBinding.Composite
  37797. const indices = {};
  37798. this._indicesByUUID = indices; // for bookkeeping
  37799. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37800. indices[ arguments[ i ].uuid ] = i;
  37801. }
  37802. this._paths = []; // inside: string
  37803. this._parsedPaths = []; // inside: { we don't care, here }
  37804. this._bindings = []; // inside: Array< PropertyBinding >
  37805. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  37806. const scope = this;
  37807. this.stats = {
  37808. objects: {
  37809. get total() {
  37810. return scope._objects.length;
  37811. },
  37812. get inUse() {
  37813. return this.total - scope.nCachedObjects_;
  37814. }
  37815. },
  37816. get bindingsPerObject() {
  37817. return scope._bindings.length;
  37818. }
  37819. };
  37820. }
  37821. /**
  37822. * Adds an arbitrary number of objects to this animation group.
  37823. *
  37824. * @param {...Object3D} arguments - The 3D objects to add.
  37825. */
  37826. add() {
  37827. const objects = this._objects,
  37828. indicesByUUID = this._indicesByUUID,
  37829. paths = this._paths,
  37830. parsedPaths = this._parsedPaths,
  37831. bindings = this._bindings,
  37832. nBindings = bindings.length;
  37833. let knownObject = undefined,
  37834. nObjects = objects.length,
  37835. nCachedObjects = this.nCachedObjects_;
  37836. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37837. const object = arguments[ i ],
  37838. uuid = object.uuid;
  37839. let index = indicesByUUID[ uuid ];
  37840. if ( index === undefined ) {
  37841. // unknown object -> add it to the ACTIVE region
  37842. index = nObjects ++;
  37843. indicesByUUID[ uuid ] = index;
  37844. objects.push( object );
  37845. // accounting is done, now do the same for all bindings
  37846. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37847. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  37848. }
  37849. } else if ( index < nCachedObjects ) {
  37850. knownObject = objects[ index ];
  37851. // move existing object to the ACTIVE region
  37852. const firstActiveIndex = -- nCachedObjects,
  37853. lastCachedObject = objects[ firstActiveIndex ];
  37854. indicesByUUID[ lastCachedObject.uuid ] = index;
  37855. objects[ index ] = lastCachedObject;
  37856. indicesByUUID[ uuid ] = firstActiveIndex;
  37857. objects[ firstActiveIndex ] = object;
  37858. // accounting is done, now do the same for all bindings
  37859. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37860. const bindingsForPath = bindings[ j ],
  37861. lastCached = bindingsForPath[ firstActiveIndex ];
  37862. let binding = bindingsForPath[ index ];
  37863. bindingsForPath[ index ] = lastCached;
  37864. if ( binding === undefined ) {
  37865. // since we do not bother to create new bindings
  37866. // for objects that are cached, the binding may
  37867. // or may not exist
  37868. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  37869. }
  37870. bindingsForPath[ firstActiveIndex ] = binding;
  37871. }
  37872. } else if ( objects[ index ] !== knownObject ) {
  37873. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  37874. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  37875. } // else the object is already where we want it to be
  37876. } // for arguments
  37877. this.nCachedObjects_ = nCachedObjects;
  37878. }
  37879. /**
  37880. * Removes an arbitrary number of objects to this animation group
  37881. *
  37882. * @param {...Object3D} arguments - The 3D objects to remove.
  37883. */
  37884. remove() {
  37885. const objects = this._objects,
  37886. indicesByUUID = this._indicesByUUID,
  37887. bindings = this._bindings,
  37888. nBindings = bindings.length;
  37889. let nCachedObjects = this.nCachedObjects_;
  37890. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37891. const object = arguments[ i ],
  37892. uuid = object.uuid,
  37893. index = indicesByUUID[ uuid ];
  37894. if ( index !== undefined && index >= nCachedObjects ) {
  37895. // move existing object into the CACHED region
  37896. const lastCachedIndex = nCachedObjects ++,
  37897. firstActiveObject = objects[ lastCachedIndex ];
  37898. indicesByUUID[ firstActiveObject.uuid ] = index;
  37899. objects[ index ] = firstActiveObject;
  37900. indicesByUUID[ uuid ] = lastCachedIndex;
  37901. objects[ lastCachedIndex ] = object;
  37902. // accounting is done, now do the same for all bindings
  37903. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37904. const bindingsForPath = bindings[ j ],
  37905. firstActive = bindingsForPath[ lastCachedIndex ],
  37906. binding = bindingsForPath[ index ];
  37907. bindingsForPath[ index ] = firstActive;
  37908. bindingsForPath[ lastCachedIndex ] = binding;
  37909. }
  37910. }
  37911. } // for arguments
  37912. this.nCachedObjects_ = nCachedObjects;
  37913. }
  37914. /**
  37915. * Deallocates all memory resources for the passed 3D objects of this animation group.
  37916. *
  37917. * @param {...Object3D} arguments - The 3D objects to uncache.
  37918. */
  37919. uncache() {
  37920. const objects = this._objects,
  37921. indicesByUUID = this._indicesByUUID,
  37922. bindings = this._bindings,
  37923. nBindings = bindings.length;
  37924. let nCachedObjects = this.nCachedObjects_,
  37925. nObjects = objects.length;
  37926. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37927. const object = arguments[ i ],
  37928. uuid = object.uuid,
  37929. index = indicesByUUID[ uuid ];
  37930. if ( index !== undefined ) {
  37931. delete indicesByUUID[ uuid ];
  37932. if ( index < nCachedObjects ) {
  37933. // object is cached, shrink the CACHED region
  37934. const firstActiveIndex = -- nCachedObjects,
  37935. lastCachedObject = objects[ firstActiveIndex ],
  37936. lastIndex = -- nObjects,
  37937. lastObject = objects[ lastIndex ];
  37938. // last cached object takes this object's place
  37939. indicesByUUID[ lastCachedObject.uuid ] = index;
  37940. objects[ index ] = lastCachedObject;
  37941. // last object goes to the activated slot and pop
  37942. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  37943. objects[ firstActiveIndex ] = lastObject;
  37944. objects.pop();
  37945. // accounting is done, now do the same for all bindings
  37946. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37947. const bindingsForPath = bindings[ j ],
  37948. lastCached = bindingsForPath[ firstActiveIndex ],
  37949. last = bindingsForPath[ lastIndex ];
  37950. bindingsForPath[ index ] = lastCached;
  37951. bindingsForPath[ firstActiveIndex ] = last;
  37952. bindingsForPath.pop();
  37953. }
  37954. } else {
  37955. // object is active, just swap with the last and pop
  37956. const lastIndex = -- nObjects,
  37957. lastObject = objects[ lastIndex ];
  37958. if ( lastIndex > 0 ) {
  37959. indicesByUUID[ lastObject.uuid ] = index;
  37960. }
  37961. objects[ index ] = lastObject;
  37962. objects.pop();
  37963. // accounting is done, now do the same for all bindings
  37964. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37965. const bindingsForPath = bindings[ j ];
  37966. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  37967. bindingsForPath.pop();
  37968. }
  37969. } // cached or active
  37970. } // if object is known
  37971. } // for arguments
  37972. this.nCachedObjects_ = nCachedObjects;
  37973. }
  37974. // Internal interface used by befriended PropertyBinding.Composite:
  37975. subscribe_( path, parsedPath ) {
  37976. // returns an array of bindings for the given path that is changed
  37977. // according to the contained objects in the group
  37978. const indicesByPath = this._bindingsIndicesByPath;
  37979. let index = indicesByPath[ path ];
  37980. const bindings = this._bindings;
  37981. if ( index !== undefined ) return bindings[ index ];
  37982. const paths = this._paths,
  37983. parsedPaths = this._parsedPaths,
  37984. objects = this._objects,
  37985. nObjects = objects.length,
  37986. nCachedObjects = this.nCachedObjects_,
  37987. bindingsForPath = new Array( nObjects );
  37988. index = bindings.length;
  37989. indicesByPath[ path ] = index;
  37990. paths.push( path );
  37991. parsedPaths.push( parsedPath );
  37992. bindings.push( bindingsForPath );
  37993. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  37994. const object = objects[ i ];
  37995. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  37996. }
  37997. return bindingsForPath;
  37998. }
  37999. unsubscribe_( path ) {
  38000. // tells the group to forget about a property path and no longer
  38001. // update the array previously obtained with 'subscribe_'
  38002. const indicesByPath = this._bindingsIndicesByPath,
  38003. index = indicesByPath[ path ];
  38004. if ( index !== undefined ) {
  38005. const paths = this._paths,
  38006. parsedPaths = this._parsedPaths,
  38007. bindings = this._bindings,
  38008. lastBindingsIndex = bindings.length - 1,
  38009. lastBindings = bindings[ lastBindingsIndex ],
  38010. lastBindingsPath = path[ lastBindingsIndex ];
  38011. indicesByPath[ lastBindingsPath ] = index;
  38012. bindings[ index ] = lastBindings;
  38013. bindings.pop();
  38014. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38015. parsedPaths.pop();
  38016. paths[ index ] = paths[ lastBindingsIndex ];
  38017. paths.pop();
  38018. }
  38019. }
  38020. }
  38021. /**
  38022. * An instance of `AnimationAction` schedules the playback of an animation which is
  38023. * stored in {@link AnimationClip}.
  38024. */
  38025. class AnimationAction {
  38026. /**
  38027. * Constructs a new animation action.
  38028. *
  38029. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38030. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38031. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38032. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38033. */
  38034. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38035. this._mixer = mixer;
  38036. this._clip = clip;
  38037. this._localRoot = localRoot;
  38038. /**
  38039. * Defines how the animation is blended/combined when two or more animations
  38040. * are simultaneously played.
  38041. *
  38042. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38043. */
  38044. this.blendMode = blendMode;
  38045. const tracks = clip.tracks,
  38046. nTracks = tracks.length,
  38047. interpolants = new Array( nTracks );
  38048. const interpolantSettings = {
  38049. endingStart: ZeroCurvatureEnding,
  38050. endingEnd: ZeroCurvatureEnding
  38051. };
  38052. for ( let i = 0; i !== nTracks; ++ i ) {
  38053. const interpolant = tracks[ i ].createInterpolant( null );
  38054. interpolants[ i ] = interpolant;
  38055. interpolant.settings = interpolantSettings;
  38056. }
  38057. this._interpolantSettings = interpolantSettings;
  38058. this._interpolants = interpolants; // bound by the mixer
  38059. // inside: PropertyMixer (managed by the mixer)
  38060. this._propertyBindings = new Array( nTracks );
  38061. this._cacheIndex = null; // for the memory manager
  38062. this._byClipCacheIndex = null; // for the memory manager
  38063. this._timeScaleInterpolant = null;
  38064. this._weightInterpolant = null;
  38065. /**
  38066. * The loop mode, set via {@link AnimationAction#setLoop}.
  38067. *
  38068. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38069. * @default LoopRepeat
  38070. */
  38071. this.loop = LoopRepeat;
  38072. this._loopCount = -1;
  38073. // global mixer time when the action is to be started
  38074. // it's set back to 'null' upon start of the action
  38075. this._startTime = null;
  38076. /**
  38077. * The local time of this action (in seconds, starting with `0`).
  38078. *
  38079. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38080. * loop state).
  38081. *
  38082. * @type {number}
  38083. * @default Infinity
  38084. */
  38085. this.time = 0;
  38086. /**
  38087. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38088. * animation to pause. Negative values cause the animation to play backwards.
  38089. *
  38090. * @type {number}
  38091. * @default 1
  38092. */
  38093. this.timeScale = 1;
  38094. this._effectiveTimeScale = 1;
  38095. /**
  38096. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38097. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38098. * several actions.
  38099. *
  38100. * @type {number}
  38101. * @default 1
  38102. */
  38103. this.weight = 1;
  38104. this._effectiveWeight = 1;
  38105. /**
  38106. * The number of repetitions of the performed clip over the course of this action.
  38107. * Can be set via {@link AnimationAction#setLoop}.
  38108. *
  38109. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38110. * `THREE:LoopOnce`.
  38111. *
  38112. * @type {number}
  38113. * @default Infinity
  38114. */
  38115. this.repetitions = Infinity;
  38116. /**
  38117. * If set to `true`, the playback of the action is paused.
  38118. *
  38119. * @type {boolean}
  38120. * @default false
  38121. */
  38122. this.paused = false;
  38123. /**
  38124. * If set to `false`, the action is disabled so it has no impact.
  38125. *
  38126. * When the action is re-enabled, the animation continues from its current
  38127. * time (setting `enabled` to `false` doesn't reset the action).
  38128. *
  38129. * @type {boolean}
  38130. * @default true
  38131. */
  38132. this.enabled = true;
  38133. /**
  38134. * If set to true the animation will automatically be paused on its last frame.
  38135. *
  38136. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38137. * to `false` when the last loop of the action has finished, so that this action has
  38138. * no further impact.
  38139. *
  38140. * Note: This member has no impact if the action is interrupted (it
  38141. * has only an effect if its last loop has really finished).
  38142. *
  38143. * @type {boolean}
  38144. * @default false
  38145. */
  38146. this.clampWhenFinished = false;
  38147. /**
  38148. * Enables smooth interpolation without separate clips for start, loop and end.
  38149. *
  38150. * @type {boolean}
  38151. * @default true
  38152. */
  38153. this.zeroSlopeAtStart = true;
  38154. /**
  38155. * Enables smooth interpolation without separate clips for start, loop and end.
  38156. *
  38157. * @type {boolean}
  38158. * @default true
  38159. */
  38160. this.zeroSlopeAtEnd = true;
  38161. }
  38162. /**
  38163. * Starts the playback of the animation.
  38164. *
  38165. * @return {AnimationAction} A reference to this animation action.
  38166. */
  38167. play() {
  38168. this._mixer._activateAction( this );
  38169. return this;
  38170. }
  38171. /**
  38172. * Stops the playback of the animation.
  38173. *
  38174. * @return {AnimationAction} A reference to this animation action.
  38175. */
  38176. stop() {
  38177. this._mixer._deactivateAction( this );
  38178. return this.reset();
  38179. }
  38180. /**
  38181. * Resets the playback of the animation.
  38182. *
  38183. * @return {AnimationAction} A reference to this animation action.
  38184. */
  38185. reset() {
  38186. this.paused = false;
  38187. this.enabled = true;
  38188. this.time = 0; // restart clip
  38189. this._loopCount = -1;// forget previous loops
  38190. this._startTime = null;// forget scheduling
  38191. return this.stopFading().stopWarping();
  38192. }
  38193. /**
  38194. * Returns `true` if the animation is running.
  38195. *
  38196. * @return {boolean} Whether the animation is running or not.
  38197. */
  38198. isRunning() {
  38199. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38200. this._startTime === null && this._mixer._isActiveAction( this );
  38201. }
  38202. /**
  38203. * Returns `true` when {@link AnimationAction#play} has been called.
  38204. *
  38205. * @return {boolean} Whether the animation is scheduled or not.
  38206. */
  38207. isScheduled() {
  38208. return this._mixer._isActiveAction( this );
  38209. }
  38210. /**
  38211. * Defines the time when the animation should start.
  38212. *
  38213. * @param {number} time - The start time in seconds.
  38214. * @return {AnimationAction} A reference to this animation action.
  38215. */
  38216. startAt( time ) {
  38217. this._startTime = time;
  38218. return this;
  38219. }
  38220. /**
  38221. * Configures the loop settings for this action.
  38222. *
  38223. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38224. * @param {number} repetitions - The number of repetitions.
  38225. * @return {AnimationAction} A reference to this animation action.
  38226. */
  38227. setLoop( mode, repetitions ) {
  38228. this.loop = mode;
  38229. this.repetitions = repetitions;
  38230. return this;
  38231. }
  38232. /**
  38233. * Sets the effective weight of this action.
  38234. *
  38235. * An action has no effect and thus an effective weight of zero when the
  38236. * action is disabled.
  38237. *
  38238. * @param {number} weight - The weight to set.
  38239. * @return {AnimationAction} A reference to this animation action.
  38240. */
  38241. setEffectiveWeight( weight ) {
  38242. this.weight = weight;
  38243. // note: same logic as when updated at runtime
  38244. this._effectiveWeight = this.enabled ? weight : 0;
  38245. return this.stopFading();
  38246. }
  38247. /**
  38248. * Returns the effective weight of this action.
  38249. *
  38250. * @return {number} The effective weight.
  38251. */
  38252. getEffectiveWeight() {
  38253. return this._effectiveWeight;
  38254. }
  38255. /**
  38256. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38257. * within the passed time interval.
  38258. *
  38259. * @param {number} duration - The duration of the fade.
  38260. * @return {AnimationAction} A reference to this animation action.
  38261. */
  38262. fadeIn( duration ) {
  38263. return this._scheduleFading( duration, 0, 1 );
  38264. }
  38265. /**
  38266. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38267. * within the passed time interval.
  38268. *
  38269. * @param {number} duration - The duration of the fade.
  38270. * @return {AnimationAction} A reference to this animation action.
  38271. */
  38272. fadeOut( duration ) {
  38273. return this._scheduleFading( duration, 1, 0 );
  38274. }
  38275. /**
  38276. * Causes this action to fade in and the given action to fade out,
  38277. * within the passed time interval.
  38278. *
  38279. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38280. * @param {number} duration - The duration of the fade.
  38281. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38282. * @return {AnimationAction} A reference to this animation action.
  38283. */
  38284. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38285. fadeOutAction.fadeOut( duration );
  38286. this.fadeIn( duration );
  38287. if ( warp === true ) {
  38288. const fadeInDuration = this._clip.duration,
  38289. fadeOutDuration = fadeOutAction._clip.duration,
  38290. startEndRatio = fadeOutDuration / fadeInDuration,
  38291. endStartRatio = fadeInDuration / fadeOutDuration;
  38292. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38293. this.warp( endStartRatio, 1.0, duration );
  38294. }
  38295. return this;
  38296. }
  38297. /**
  38298. * Causes this action to fade out and the given action to fade in,
  38299. * within the passed time interval.
  38300. *
  38301. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38302. * @param {number} duration - The duration of the fade.
  38303. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38304. * @return {AnimationAction} A reference to this animation action.
  38305. */
  38306. crossFadeTo( fadeInAction, duration, warp = false ) {
  38307. return fadeInAction.crossFadeFrom( this, duration, warp );
  38308. }
  38309. /**
  38310. * Stops any fading which is applied to this action.
  38311. *
  38312. * @return {AnimationAction} A reference to this animation action.
  38313. */
  38314. stopFading() {
  38315. const weightInterpolant = this._weightInterpolant;
  38316. if ( weightInterpolant !== null ) {
  38317. this._weightInterpolant = null;
  38318. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38319. }
  38320. return this;
  38321. }
  38322. /**
  38323. * Sets the effective time scale of this action.
  38324. *
  38325. * An action has no effect and thus an effective time scale of zero when the
  38326. * action is paused.
  38327. *
  38328. * @param {number} timeScale - The time scale to set.
  38329. * @return {AnimationAction} A reference to this animation action.
  38330. */
  38331. setEffectiveTimeScale( timeScale ) {
  38332. this.timeScale = timeScale;
  38333. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38334. return this.stopWarping();
  38335. }
  38336. /**
  38337. * Returns the effective time scale of this action.
  38338. *
  38339. * @return {number} The effective time scale.
  38340. */
  38341. getEffectiveTimeScale() {
  38342. return this._effectiveTimeScale;
  38343. }
  38344. /**
  38345. * Sets the duration for a single loop of this action.
  38346. *
  38347. * @param {number} duration - The duration to set.
  38348. * @return {AnimationAction} A reference to this animation action.
  38349. */
  38350. setDuration( duration ) {
  38351. this.timeScale = this._clip.duration / duration;
  38352. return this.stopWarping();
  38353. }
  38354. /**
  38355. * Synchronizes this action with the passed other action.
  38356. *
  38357. * @param {AnimationAction} action - The action to sync with.
  38358. * @return {AnimationAction} A reference to this animation action.
  38359. */
  38360. syncWith( action ) {
  38361. this.time = action.time;
  38362. this.timeScale = action.timeScale;
  38363. return this.stopWarping();
  38364. }
  38365. /**
  38366. * Decelerates this animation's speed to `0` within the passed time interval.
  38367. *
  38368. * @param {number} duration - The duration.
  38369. * @return {AnimationAction} A reference to this animation action.
  38370. */
  38371. halt( duration ) {
  38372. return this.warp( this._effectiveTimeScale, 0, duration );
  38373. }
  38374. /**
  38375. * Changes the playback speed, within the passed time interval, by modifying
  38376. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38377. * `endTimeScale`.
  38378. *
  38379. * @param {number} startTimeScale - The start time scale.
  38380. * @param {number} endTimeScale - The end time scale.
  38381. * @param {number} duration - The duration.
  38382. * @return {AnimationAction} A reference to this animation action.
  38383. */
  38384. warp( startTimeScale, endTimeScale, duration ) {
  38385. const mixer = this._mixer,
  38386. now = mixer.time,
  38387. timeScale = this.timeScale;
  38388. let interpolant = this._timeScaleInterpolant;
  38389. if ( interpolant === null ) {
  38390. interpolant = mixer._lendControlInterpolant();
  38391. this._timeScaleInterpolant = interpolant;
  38392. }
  38393. const times = interpolant.parameterPositions,
  38394. values = interpolant.sampleValues;
  38395. times[ 0 ] = now;
  38396. times[ 1 ] = now + duration;
  38397. values[ 0 ] = startTimeScale / timeScale;
  38398. values[ 1 ] = endTimeScale / timeScale;
  38399. return this;
  38400. }
  38401. /**
  38402. * Stops any scheduled warping which is applied to this action.
  38403. *
  38404. * @return {AnimationAction} A reference to this animation action.
  38405. */
  38406. stopWarping() {
  38407. const timeScaleInterpolant = this._timeScaleInterpolant;
  38408. if ( timeScaleInterpolant !== null ) {
  38409. this._timeScaleInterpolant = null;
  38410. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38411. }
  38412. return this;
  38413. }
  38414. /**
  38415. * Returns the animation mixer of this animation action.
  38416. *
  38417. * @return {AnimationMixer} The animation mixer.
  38418. */
  38419. getMixer() {
  38420. return this._mixer;
  38421. }
  38422. /**
  38423. * Returns the animation clip of this animation action.
  38424. *
  38425. * @return {AnimationClip} The animation clip.
  38426. */
  38427. getClip() {
  38428. return this._clip;
  38429. }
  38430. /**
  38431. * Returns the root object of this animation action.
  38432. *
  38433. * @return {Object3D} The root object.
  38434. */
  38435. getRoot() {
  38436. return this._localRoot || this._mixer._root;
  38437. }
  38438. // Interna
  38439. _update( time, deltaTime, timeDirection, accuIndex ) {
  38440. // called by the mixer
  38441. if ( ! this.enabled ) {
  38442. // call ._updateWeight() to update ._effectiveWeight
  38443. this._updateWeight( time );
  38444. return;
  38445. }
  38446. const startTime = this._startTime;
  38447. if ( startTime !== null ) {
  38448. // check for scheduled start of action
  38449. const timeRunning = ( time - startTime ) * timeDirection;
  38450. if ( timeRunning < 0 || timeDirection === 0 ) {
  38451. deltaTime = 0;
  38452. } else {
  38453. this._startTime = null; // unschedule
  38454. deltaTime = timeDirection * timeRunning;
  38455. }
  38456. }
  38457. // apply time scale and advance time
  38458. deltaTime *= this._updateTimeScale( time );
  38459. const clipTime = this._updateTime( deltaTime );
  38460. // note: _updateTime may disable the action resulting in
  38461. // an effective weight of 0
  38462. const weight = this._updateWeight( time );
  38463. if ( weight > 0 ) {
  38464. const interpolants = this._interpolants;
  38465. const propertyMixers = this._propertyBindings;
  38466. switch ( this.blendMode ) {
  38467. case AdditiveAnimationBlendMode:
  38468. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38469. interpolants[ j ].evaluate( clipTime );
  38470. propertyMixers[ j ].accumulateAdditive( weight );
  38471. }
  38472. break;
  38473. case NormalAnimationBlendMode:
  38474. default:
  38475. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38476. interpolants[ j ].evaluate( clipTime );
  38477. propertyMixers[ j ].accumulate( accuIndex, weight );
  38478. }
  38479. }
  38480. }
  38481. }
  38482. _updateWeight( time ) {
  38483. let weight = 0;
  38484. if ( this.enabled ) {
  38485. weight = this.weight;
  38486. const interpolant = this._weightInterpolant;
  38487. if ( interpolant !== null ) {
  38488. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38489. weight *= interpolantValue;
  38490. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38491. this.stopFading();
  38492. if ( interpolantValue === 0 ) {
  38493. // faded out, disable
  38494. this.enabled = false;
  38495. }
  38496. }
  38497. }
  38498. }
  38499. this._effectiveWeight = weight;
  38500. return weight;
  38501. }
  38502. _updateTimeScale( time ) {
  38503. let timeScale = 0;
  38504. if ( ! this.paused ) {
  38505. timeScale = this.timeScale;
  38506. const interpolant = this._timeScaleInterpolant;
  38507. if ( interpolant !== null ) {
  38508. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38509. timeScale *= interpolantValue;
  38510. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38511. this.stopWarping();
  38512. if ( timeScale === 0 ) {
  38513. // motion has halted, pause
  38514. this.paused = true;
  38515. } else {
  38516. // warp done - apply final time scale
  38517. this.timeScale = timeScale;
  38518. }
  38519. }
  38520. }
  38521. }
  38522. this._effectiveTimeScale = timeScale;
  38523. return timeScale;
  38524. }
  38525. _updateTime( deltaTime ) {
  38526. const duration = this._clip.duration;
  38527. const loop = this.loop;
  38528. let time = this.time + deltaTime;
  38529. let loopCount = this._loopCount;
  38530. const pingPong = ( loop === LoopPingPong );
  38531. if ( deltaTime === 0 ) {
  38532. if ( loopCount === -1 ) return time;
  38533. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38534. }
  38535. if ( loop === LoopOnce ) {
  38536. if ( loopCount === -1 ) {
  38537. // just started
  38538. this._loopCount = 0;
  38539. this._setEndings( true, true, false );
  38540. }
  38541. handle_stop: {
  38542. if ( time >= duration ) {
  38543. time = duration;
  38544. } else if ( time < 0 ) {
  38545. time = 0;
  38546. } else {
  38547. this.time = time;
  38548. break handle_stop;
  38549. }
  38550. if ( this.clampWhenFinished ) this.paused = true;
  38551. else this.enabled = false;
  38552. this.time = time;
  38553. this._mixer.dispatchEvent( {
  38554. type: 'finished', action: this,
  38555. direction: deltaTime < 0 ? -1 : 1
  38556. } );
  38557. }
  38558. } else { // repetitive Repeat or PingPong
  38559. if ( loopCount === -1 ) {
  38560. // just started
  38561. if ( deltaTime >= 0 ) {
  38562. loopCount = 0;
  38563. this._setEndings( true, this.repetitions === 0, pingPong );
  38564. } else {
  38565. // when looping in reverse direction, the initial
  38566. // transition through zero counts as a repetition,
  38567. // so leave loopCount at -1
  38568. this._setEndings( this.repetitions === 0, true, pingPong );
  38569. }
  38570. }
  38571. if ( time >= duration || time < 0 ) {
  38572. // wrap around
  38573. const loopDelta = Math.floor( time / duration ); // signed
  38574. time -= duration * loopDelta;
  38575. loopCount += Math.abs( loopDelta );
  38576. const pending = this.repetitions - loopCount;
  38577. if ( pending <= 0 ) {
  38578. // have to stop (switch state, clamp time, fire event)
  38579. if ( this.clampWhenFinished ) this.paused = true;
  38580. else this.enabled = false;
  38581. time = deltaTime > 0 ? duration : 0;
  38582. this.time = time;
  38583. this._mixer.dispatchEvent( {
  38584. type: 'finished', action: this,
  38585. direction: deltaTime > 0 ? 1 : -1
  38586. } );
  38587. } else {
  38588. // keep running
  38589. if ( pending === 1 ) {
  38590. // entering the last round
  38591. const atStart = deltaTime < 0;
  38592. this._setEndings( atStart, ! atStart, pingPong );
  38593. } else {
  38594. this._setEndings( false, false, pingPong );
  38595. }
  38596. this._loopCount = loopCount;
  38597. this.time = time;
  38598. this._mixer.dispatchEvent( {
  38599. type: 'loop', action: this, loopDelta: loopDelta
  38600. } );
  38601. }
  38602. } else {
  38603. this.time = time;
  38604. }
  38605. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38606. // invert time for the "pong round"
  38607. return duration - time;
  38608. }
  38609. }
  38610. return time;
  38611. }
  38612. _setEndings( atStart, atEnd, pingPong ) {
  38613. const settings = this._interpolantSettings;
  38614. if ( pingPong ) {
  38615. settings.endingStart = ZeroSlopeEnding;
  38616. settings.endingEnd = ZeroSlopeEnding;
  38617. } else {
  38618. // assuming for LoopOnce atStart == atEnd == true
  38619. if ( atStart ) {
  38620. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38621. } else {
  38622. settings.endingStart = WrapAroundEnding;
  38623. }
  38624. if ( atEnd ) {
  38625. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38626. } else {
  38627. settings.endingEnd = WrapAroundEnding;
  38628. }
  38629. }
  38630. }
  38631. _scheduleFading( duration, weightNow, weightThen ) {
  38632. const mixer = this._mixer, now = mixer.time;
  38633. let interpolant = this._weightInterpolant;
  38634. if ( interpolant === null ) {
  38635. interpolant = mixer._lendControlInterpolant();
  38636. this._weightInterpolant = interpolant;
  38637. }
  38638. const times = interpolant.parameterPositions,
  38639. values = interpolant.sampleValues;
  38640. times[ 0 ] = now;
  38641. values[ 0 ] = weightNow;
  38642. times[ 1 ] = now + duration;
  38643. values[ 1 ] = weightThen;
  38644. return this;
  38645. }
  38646. }
  38647. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38648. /**
  38649. * `AnimationMixer` is a player for animations on a particular object in
  38650. * the scene. When multiple objects in the scene are animated independently,
  38651. * one `AnimationMixer` may be used for each object.
  38652. */
  38653. class AnimationMixer extends EventDispatcher {
  38654. /**
  38655. * Constructs a new animation mixer.
  38656. *
  38657. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38658. */
  38659. constructor( root ) {
  38660. super();
  38661. this._root = root;
  38662. this._initMemoryManager();
  38663. this._accuIndex = 0;
  38664. /**
  38665. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38666. *
  38667. * @type {number}
  38668. * @default 0
  38669. */
  38670. this.time = 0;
  38671. /**
  38672. * A scaling factor for the global time.
  38673. *
  38674. * Note: Setting this member to `0` and later back to `1` is a
  38675. * possibility to pause/unpause all actions that are controlled by this
  38676. * mixer.
  38677. *
  38678. * @type {number}
  38679. * @default 1
  38680. */
  38681. this.timeScale = 1.0;
  38682. }
  38683. _bindAction( action, prototypeAction ) {
  38684. const root = action._localRoot || this._root,
  38685. tracks = action._clip.tracks,
  38686. nTracks = tracks.length,
  38687. bindings = action._propertyBindings,
  38688. interpolants = action._interpolants,
  38689. rootUuid = root.uuid,
  38690. bindingsByRoot = this._bindingsByRootAndName;
  38691. let bindingsByName = bindingsByRoot[ rootUuid ];
  38692. if ( bindingsByName === undefined ) {
  38693. bindingsByName = {};
  38694. bindingsByRoot[ rootUuid ] = bindingsByName;
  38695. }
  38696. for ( let i = 0; i !== nTracks; ++ i ) {
  38697. const track = tracks[ i ],
  38698. trackName = track.name;
  38699. let binding = bindingsByName[ trackName ];
  38700. if ( binding !== undefined ) {
  38701. ++ binding.referenceCount;
  38702. bindings[ i ] = binding;
  38703. } else {
  38704. binding = bindings[ i ];
  38705. if ( binding !== undefined ) {
  38706. // existing binding, make sure the cache knows
  38707. if ( binding._cacheIndex === null ) {
  38708. ++ binding.referenceCount;
  38709. this._addInactiveBinding( binding, rootUuid, trackName );
  38710. }
  38711. continue;
  38712. }
  38713. const path = prototypeAction && prototypeAction.
  38714. _propertyBindings[ i ].binding.parsedPath;
  38715. binding = new PropertyMixer(
  38716. PropertyBinding.create( root, trackName, path ),
  38717. track.ValueTypeName, track.getValueSize() );
  38718. ++ binding.referenceCount;
  38719. this._addInactiveBinding( binding, rootUuid, trackName );
  38720. bindings[ i ] = binding;
  38721. }
  38722. interpolants[ i ].resultBuffer = binding.buffer;
  38723. }
  38724. }
  38725. _activateAction( action ) {
  38726. if ( ! this._isActiveAction( action ) ) {
  38727. if ( action._cacheIndex === null ) {
  38728. // this action has been forgotten by the cache, but the user
  38729. // appears to be still using it -> rebind
  38730. const rootUuid = ( action._localRoot || this._root ).uuid,
  38731. clipUuid = action._clip.uuid,
  38732. actionsForClip = this._actionsByClip[ clipUuid ];
  38733. this._bindAction( action,
  38734. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38735. this._addInactiveAction( action, clipUuid, rootUuid );
  38736. }
  38737. const bindings = action._propertyBindings;
  38738. // increment reference counts / sort out state
  38739. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38740. const binding = bindings[ i ];
  38741. if ( binding.useCount ++ === 0 ) {
  38742. this._lendBinding( binding );
  38743. binding.saveOriginalState();
  38744. }
  38745. }
  38746. this._lendAction( action );
  38747. }
  38748. }
  38749. _deactivateAction( action ) {
  38750. if ( this._isActiveAction( action ) ) {
  38751. const bindings = action._propertyBindings;
  38752. // decrement reference counts / sort out state
  38753. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38754. const binding = bindings[ i ];
  38755. if ( -- binding.useCount === 0 ) {
  38756. binding.restoreOriginalState();
  38757. this._takeBackBinding( binding );
  38758. }
  38759. }
  38760. this._takeBackAction( action );
  38761. }
  38762. }
  38763. // Memory manager
  38764. _initMemoryManager() {
  38765. this._actions = []; // 'nActiveActions' followed by inactive ones
  38766. this._nActiveActions = 0;
  38767. this._actionsByClip = {};
  38768. // inside:
  38769. // {
  38770. // knownActions: Array< AnimationAction > - used as prototypes
  38771. // actionByRoot: AnimationAction - lookup
  38772. // }
  38773. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38774. this._nActiveBindings = 0;
  38775. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38776. this._controlInterpolants = []; // same game as above
  38777. this._nActiveControlInterpolants = 0;
  38778. const scope = this;
  38779. this.stats = {
  38780. actions: {
  38781. get total() {
  38782. return scope._actions.length;
  38783. },
  38784. get inUse() {
  38785. return scope._nActiveActions;
  38786. }
  38787. },
  38788. bindings: {
  38789. get total() {
  38790. return scope._bindings.length;
  38791. },
  38792. get inUse() {
  38793. return scope._nActiveBindings;
  38794. }
  38795. },
  38796. controlInterpolants: {
  38797. get total() {
  38798. return scope._controlInterpolants.length;
  38799. },
  38800. get inUse() {
  38801. return scope._nActiveControlInterpolants;
  38802. }
  38803. }
  38804. };
  38805. }
  38806. // Memory management for AnimationAction objects
  38807. _isActiveAction( action ) {
  38808. const index = action._cacheIndex;
  38809. return index !== null && index < this._nActiveActions;
  38810. }
  38811. _addInactiveAction( action, clipUuid, rootUuid ) {
  38812. const actions = this._actions,
  38813. actionsByClip = this._actionsByClip;
  38814. let actionsForClip = actionsByClip[ clipUuid ];
  38815. if ( actionsForClip === undefined ) {
  38816. actionsForClip = {
  38817. knownActions: [ action ],
  38818. actionByRoot: {}
  38819. };
  38820. action._byClipCacheIndex = 0;
  38821. actionsByClip[ clipUuid ] = actionsForClip;
  38822. } else {
  38823. const knownActions = actionsForClip.knownActions;
  38824. action._byClipCacheIndex = knownActions.length;
  38825. knownActions.push( action );
  38826. }
  38827. action._cacheIndex = actions.length;
  38828. actions.push( action );
  38829. actionsForClip.actionByRoot[ rootUuid ] = action;
  38830. }
  38831. _removeInactiveAction( action ) {
  38832. const actions = this._actions,
  38833. lastInactiveAction = actions[ actions.length - 1 ],
  38834. cacheIndex = action._cacheIndex;
  38835. lastInactiveAction._cacheIndex = cacheIndex;
  38836. actions[ cacheIndex ] = lastInactiveAction;
  38837. actions.pop();
  38838. action._cacheIndex = null;
  38839. const clipUuid = action._clip.uuid,
  38840. actionsByClip = this._actionsByClip,
  38841. actionsForClip = actionsByClip[ clipUuid ],
  38842. knownActionsForClip = actionsForClip.knownActions,
  38843. lastKnownAction =
  38844. knownActionsForClip[ knownActionsForClip.length - 1 ],
  38845. byClipCacheIndex = action._byClipCacheIndex;
  38846. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  38847. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  38848. knownActionsForClip.pop();
  38849. action._byClipCacheIndex = null;
  38850. const actionByRoot = actionsForClip.actionByRoot,
  38851. rootUuid = ( action._localRoot || this._root ).uuid;
  38852. delete actionByRoot[ rootUuid ];
  38853. if ( knownActionsForClip.length === 0 ) {
  38854. delete actionsByClip[ clipUuid ];
  38855. }
  38856. this._removeInactiveBindingsForAction( action );
  38857. }
  38858. _removeInactiveBindingsForAction( action ) {
  38859. const bindings = action._propertyBindings;
  38860. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38861. const binding = bindings[ i ];
  38862. if ( -- binding.referenceCount === 0 ) {
  38863. this._removeInactiveBinding( binding );
  38864. }
  38865. }
  38866. }
  38867. _lendAction( action ) {
  38868. // [ active actions | inactive actions ]
  38869. // [ active actions >| inactive actions ]
  38870. // s a
  38871. // <-swap->
  38872. // a s
  38873. const actions = this._actions,
  38874. prevIndex = action._cacheIndex,
  38875. lastActiveIndex = this._nActiveActions ++,
  38876. firstInactiveAction = actions[ lastActiveIndex ];
  38877. action._cacheIndex = lastActiveIndex;
  38878. actions[ lastActiveIndex ] = action;
  38879. firstInactiveAction._cacheIndex = prevIndex;
  38880. actions[ prevIndex ] = firstInactiveAction;
  38881. }
  38882. _takeBackAction( action ) {
  38883. // [ active actions | inactive actions ]
  38884. // [ active actions |< inactive actions ]
  38885. // a s
  38886. // <-swap->
  38887. // s a
  38888. const actions = this._actions,
  38889. prevIndex = action._cacheIndex,
  38890. firstInactiveIndex = -- this._nActiveActions,
  38891. lastActiveAction = actions[ firstInactiveIndex ];
  38892. action._cacheIndex = firstInactiveIndex;
  38893. actions[ firstInactiveIndex ] = action;
  38894. lastActiveAction._cacheIndex = prevIndex;
  38895. actions[ prevIndex ] = lastActiveAction;
  38896. }
  38897. // Memory management for PropertyMixer objects
  38898. _addInactiveBinding( binding, rootUuid, trackName ) {
  38899. const bindingsByRoot = this._bindingsByRootAndName,
  38900. bindings = this._bindings;
  38901. let bindingByName = bindingsByRoot[ rootUuid ];
  38902. if ( bindingByName === undefined ) {
  38903. bindingByName = {};
  38904. bindingsByRoot[ rootUuid ] = bindingByName;
  38905. }
  38906. bindingByName[ trackName ] = binding;
  38907. binding._cacheIndex = bindings.length;
  38908. bindings.push( binding );
  38909. }
  38910. _removeInactiveBinding( binding ) {
  38911. const bindings = this._bindings,
  38912. propBinding = binding.binding,
  38913. rootUuid = propBinding.rootNode.uuid,
  38914. trackName = propBinding.path,
  38915. bindingsByRoot = this._bindingsByRootAndName,
  38916. bindingByName = bindingsByRoot[ rootUuid ],
  38917. lastInactiveBinding = bindings[ bindings.length - 1 ],
  38918. cacheIndex = binding._cacheIndex;
  38919. lastInactiveBinding._cacheIndex = cacheIndex;
  38920. bindings[ cacheIndex ] = lastInactiveBinding;
  38921. bindings.pop();
  38922. delete bindingByName[ trackName ];
  38923. if ( Object.keys( bindingByName ).length === 0 ) {
  38924. delete bindingsByRoot[ rootUuid ];
  38925. }
  38926. }
  38927. _lendBinding( binding ) {
  38928. const bindings = this._bindings,
  38929. prevIndex = binding._cacheIndex,
  38930. lastActiveIndex = this._nActiveBindings ++,
  38931. firstInactiveBinding = bindings[ lastActiveIndex ];
  38932. binding._cacheIndex = lastActiveIndex;
  38933. bindings[ lastActiveIndex ] = binding;
  38934. firstInactiveBinding._cacheIndex = prevIndex;
  38935. bindings[ prevIndex ] = firstInactiveBinding;
  38936. }
  38937. _takeBackBinding( binding ) {
  38938. const bindings = this._bindings,
  38939. prevIndex = binding._cacheIndex,
  38940. firstInactiveIndex = -- this._nActiveBindings,
  38941. lastActiveBinding = bindings[ firstInactiveIndex ];
  38942. binding._cacheIndex = firstInactiveIndex;
  38943. bindings[ firstInactiveIndex ] = binding;
  38944. lastActiveBinding._cacheIndex = prevIndex;
  38945. bindings[ prevIndex ] = lastActiveBinding;
  38946. }
  38947. // Memory management of Interpolants for weight and time scale
  38948. _lendControlInterpolant() {
  38949. const interpolants = this._controlInterpolants,
  38950. lastActiveIndex = this._nActiveControlInterpolants ++;
  38951. let interpolant = interpolants[ lastActiveIndex ];
  38952. if ( interpolant === undefined ) {
  38953. interpolant = new LinearInterpolant(
  38954. new Float32Array( 2 ), new Float32Array( 2 ),
  38955. 1, _controlInterpolantsResultBuffer );
  38956. interpolant.__cacheIndex = lastActiveIndex;
  38957. interpolants[ lastActiveIndex ] = interpolant;
  38958. }
  38959. return interpolant;
  38960. }
  38961. _takeBackControlInterpolant( interpolant ) {
  38962. const interpolants = this._controlInterpolants,
  38963. prevIndex = interpolant.__cacheIndex,
  38964. firstInactiveIndex = -- this._nActiveControlInterpolants,
  38965. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  38966. interpolant.__cacheIndex = firstInactiveIndex;
  38967. interpolants[ firstInactiveIndex ] = interpolant;
  38968. lastActiveInterpolant.__cacheIndex = prevIndex;
  38969. interpolants[ prevIndex ] = lastActiveInterpolant;
  38970. }
  38971. /**
  38972. * Returns an instance of {@link AnimationAction} for the passed clip.
  38973. *
  38974. * If an action fitting the clip and root parameters doesn't yet exist, it
  38975. * will be created by this method. Calling this method several times with the
  38976. * same clip and root parameters always returns the same action.
  38977. *
  38978. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38979. * @param {Object3D} [optionalRoot] - An alternative root object.
  38980. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38981. * @return {?AnimationAction} The animation action.
  38982. */
  38983. clipAction( clip, optionalRoot, blendMode ) {
  38984. const root = optionalRoot || this._root,
  38985. rootUuid = root.uuid;
  38986. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  38987. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  38988. const actionsForClip = this._actionsByClip[ clipUuid ];
  38989. let prototypeAction = null;
  38990. if ( blendMode === undefined ) {
  38991. if ( clipObject !== null ) {
  38992. blendMode = clipObject.blendMode;
  38993. } else {
  38994. blendMode = NormalAnimationBlendMode;
  38995. }
  38996. }
  38997. if ( actionsForClip !== undefined ) {
  38998. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  38999. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39000. return existingAction;
  39001. }
  39002. // we know the clip, so we don't have to parse all
  39003. // the bindings again but can just copy
  39004. prototypeAction = actionsForClip.knownActions[ 0 ];
  39005. // also, take the clip from the prototype action
  39006. if ( clipObject === null )
  39007. clipObject = prototypeAction._clip;
  39008. }
  39009. // clip must be known when specified via string
  39010. if ( clipObject === null ) return null;
  39011. // allocate all resources required to run it
  39012. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39013. this._bindAction( newAction, prototypeAction );
  39014. // and make the action known to the memory manager
  39015. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39016. return newAction;
  39017. }
  39018. /**
  39019. * Returns an existing animation action for the passed clip.
  39020. *
  39021. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39022. * @param {Object3D} [optionalRoot] - An alternative root object.
  39023. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39024. */
  39025. existingAction( clip, optionalRoot ) {
  39026. const root = optionalRoot || this._root,
  39027. rootUuid = root.uuid,
  39028. clipObject = typeof clip === 'string' ?
  39029. AnimationClip.findByName( root, clip ) : clip,
  39030. clipUuid = clipObject ? clipObject.uuid : clip,
  39031. actionsForClip = this._actionsByClip[ clipUuid ];
  39032. if ( actionsForClip !== undefined ) {
  39033. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39034. }
  39035. return null;
  39036. }
  39037. /**
  39038. * Deactivates all previously scheduled actions on this mixer.
  39039. *
  39040. * @return {AnimationMixer} A reference to thi animation mixer.
  39041. */
  39042. stopAllAction() {
  39043. const actions = this._actions,
  39044. nActions = this._nActiveActions;
  39045. for ( let i = nActions - 1; i >= 0; -- i ) {
  39046. actions[ i ].stop();
  39047. }
  39048. return this;
  39049. }
  39050. /**
  39051. * Advances the global mixer time and updates the animation.
  39052. *
  39053. * This is usually done in the render loop by passing the delta
  39054. * time from {@link Clock} or {@link Timer}.
  39055. *
  39056. * @param {number} deltaTime - The delta time in seconds.
  39057. * @return {AnimationMixer} A reference to thi animation mixer.
  39058. */
  39059. update( deltaTime ) {
  39060. deltaTime *= this.timeScale;
  39061. const actions = this._actions,
  39062. nActions = this._nActiveActions,
  39063. time = this.time += deltaTime,
  39064. timeDirection = Math.sign( deltaTime ),
  39065. accuIndex = this._accuIndex ^= 1;
  39066. // run active actions
  39067. for ( let i = 0; i !== nActions; ++ i ) {
  39068. const action = actions[ i ];
  39069. action._update( time, deltaTime, timeDirection, accuIndex );
  39070. }
  39071. // update scene graph
  39072. const bindings = this._bindings,
  39073. nBindings = this._nActiveBindings;
  39074. for ( let i = 0; i !== nBindings; ++ i ) {
  39075. bindings[ i ].apply( accuIndex );
  39076. }
  39077. return this;
  39078. }
  39079. /**
  39080. * Sets the global mixer to a specific time and updates the animation accordingly.
  39081. *
  39082. * This is useful when you need to jump to an exact time in an animation. The
  39083. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39084. *
  39085. * @param {number} time - The time to set in seconds.
  39086. * @return {AnimationMixer} A reference to thi animation mixer.
  39087. */
  39088. setTime( time ) {
  39089. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39090. for ( let i = 0; i < this._actions.length; i ++ ) {
  39091. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39092. }
  39093. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39094. }
  39095. /**
  39096. * Returns this mixer's root object.
  39097. *
  39098. * @return {Object3D} The mixer's root object.
  39099. */
  39100. getRoot() {
  39101. return this._root;
  39102. }
  39103. /**
  39104. * Deallocates all memory resources for a clip. Before using this method make
  39105. * sure to call {@link AnimationAction#stop} for all related actions.
  39106. *
  39107. * @param {AnimationClip} clip - The clip to uncache.
  39108. */
  39109. uncacheClip( clip ) {
  39110. const actions = this._actions,
  39111. clipUuid = clip.uuid,
  39112. actionsByClip = this._actionsByClip,
  39113. actionsForClip = actionsByClip[ clipUuid ];
  39114. if ( actionsForClip !== undefined ) {
  39115. // note: just calling _removeInactiveAction would mess up the
  39116. // iteration state and also require updating the state we can
  39117. // just throw away
  39118. const actionsToRemove = actionsForClip.knownActions;
  39119. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39120. const action = actionsToRemove[ i ];
  39121. this._deactivateAction( action );
  39122. const cacheIndex = action._cacheIndex,
  39123. lastInactiveAction = actions[ actions.length - 1 ];
  39124. action._cacheIndex = null;
  39125. action._byClipCacheIndex = null;
  39126. lastInactiveAction._cacheIndex = cacheIndex;
  39127. actions[ cacheIndex ] = lastInactiveAction;
  39128. actions.pop();
  39129. this._removeInactiveBindingsForAction( action );
  39130. }
  39131. delete actionsByClip[ clipUuid ];
  39132. }
  39133. }
  39134. /**
  39135. * Deallocates all memory resources for a root object. Before using this
  39136. * method make sure to call {@link AnimationAction#stop} for all related
  39137. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39138. * mixer operates on a single root.
  39139. *
  39140. * @param {Object3D} root - The root object to uncache.
  39141. */
  39142. uncacheRoot( root ) {
  39143. const rootUuid = root.uuid,
  39144. actionsByClip = this._actionsByClip;
  39145. for ( const clipUuid in actionsByClip ) {
  39146. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39147. action = actionByRoot[ rootUuid ];
  39148. if ( action !== undefined ) {
  39149. this._deactivateAction( action );
  39150. this._removeInactiveAction( action );
  39151. }
  39152. }
  39153. const bindingsByRoot = this._bindingsByRootAndName,
  39154. bindingByName = bindingsByRoot[ rootUuid ];
  39155. if ( bindingByName !== undefined ) {
  39156. for ( const trackName in bindingByName ) {
  39157. const binding = bindingByName[ trackName ];
  39158. binding.restoreOriginalState();
  39159. this._removeInactiveBinding( binding );
  39160. }
  39161. }
  39162. }
  39163. /**
  39164. * Deallocates all memory resources for an action. The action is identified by the
  39165. * given clip and an optional root object. Before using this method make
  39166. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39167. *
  39168. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39169. * @param {Object3D} [optionalRoot] - An alternative root object.
  39170. */
  39171. uncacheAction( clip, optionalRoot ) {
  39172. const action = this.existingAction( clip, optionalRoot );
  39173. if ( action !== null ) {
  39174. this._deactivateAction( action );
  39175. this._removeInactiveAction( action );
  39176. }
  39177. }
  39178. }
  39179. /**
  39180. * Represents a 3D render target.
  39181. *
  39182. * @augments RenderTarget
  39183. */
  39184. class RenderTarget3D extends RenderTarget {
  39185. /**
  39186. * Constructs a new 3D render target.
  39187. *
  39188. * @param {number} [width=1] - The width of the render target.
  39189. * @param {number} [height=1] - The height of the render target.
  39190. * @param {number} [depth=1] - The height of the render target.
  39191. * @param {RenderTarget~Options} [options] - The configuration object.
  39192. */
  39193. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39194. super( width, height, options );
  39195. /**
  39196. * This flag can be used for type testing.
  39197. *
  39198. * @type {boolean}
  39199. * @readonly
  39200. * @default true
  39201. */
  39202. this.isRenderTarget3D = true;
  39203. this.depth = depth;
  39204. /**
  39205. * Overwritten with a different texture type.
  39206. *
  39207. * @type {Data3DTexture}
  39208. */
  39209. this.texture = new Data3DTexture( null, width, height, depth );
  39210. this._setTextureOptions( options );
  39211. this.texture.isRenderTargetTexture = true;
  39212. }
  39213. }
  39214. /**
  39215. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39216. *
  39217. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39218. * ```js
  39219. * uniforms: {
  39220. * time: { value: 1.0 },
  39221. * resolution: new Uniform( new Vector2() )
  39222. * };
  39223. * ```
  39224. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39225. * in {@link WebGLRenderer}.
  39226. */
  39227. class Uniform {
  39228. /**
  39229. * Constructs a new uniform.
  39230. *
  39231. * @param {any} value - The uniform value.
  39232. */
  39233. constructor( value ) {
  39234. /**
  39235. * The uniform value.
  39236. *
  39237. * @type {any}
  39238. */
  39239. this.value = value;
  39240. }
  39241. /**
  39242. * Returns a new uniform with copied values from this instance.
  39243. * If the value has a `clone()` method, the value is cloned as well.
  39244. *
  39245. * @return {Uniform} A clone of this instance.
  39246. */
  39247. clone() {
  39248. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39249. }
  39250. }
  39251. let _id = 0;
  39252. /**
  39253. * A class for managing multiple uniforms in a single group. The renderer will process
  39254. * such a definition as a single UBO.
  39255. *
  39256. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39257. * in {@link WebGLRenderer}.
  39258. *
  39259. * @augments EventDispatcher
  39260. */
  39261. class UniformsGroup extends EventDispatcher {
  39262. /**
  39263. * Constructs a new uniforms group.
  39264. */
  39265. constructor() {
  39266. super();
  39267. /**
  39268. * This flag can be used for type testing.
  39269. *
  39270. * @type {boolean}
  39271. * @readonly
  39272. * @default true
  39273. */
  39274. this.isUniformsGroup = true;
  39275. /**
  39276. * The ID of the 3D object.
  39277. *
  39278. * @name UniformsGroup#id
  39279. * @type {number}
  39280. * @readonly
  39281. */
  39282. Object.defineProperty( this, 'id', { value: _id ++ } );
  39283. /**
  39284. * The name of the uniforms group.
  39285. *
  39286. * @type {string}
  39287. */
  39288. this.name = '';
  39289. /**
  39290. * The buffer usage.
  39291. *
  39292. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39293. * @default StaticDrawUsage
  39294. */
  39295. this.usage = StaticDrawUsage;
  39296. /**
  39297. * An array holding the uniforms.
  39298. *
  39299. * @type {Array<Uniform>}
  39300. */
  39301. this.uniforms = [];
  39302. }
  39303. /**
  39304. * Adds the given uniform to this uniforms group.
  39305. *
  39306. * @param {Uniform} uniform - The uniform to add.
  39307. * @return {UniformsGroup} A reference to this uniforms group.
  39308. */
  39309. add( uniform ) {
  39310. this.uniforms.push( uniform );
  39311. return this;
  39312. }
  39313. /**
  39314. * Removes the given uniform from this uniforms group.
  39315. *
  39316. * @param {Uniform} uniform - The uniform to remove.
  39317. * @return {UniformsGroup} A reference to this uniforms group.
  39318. */
  39319. remove( uniform ) {
  39320. const index = this.uniforms.indexOf( uniform );
  39321. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39322. return this;
  39323. }
  39324. /**
  39325. * Sets the name of this uniforms group.
  39326. *
  39327. * @param {string} name - The name to set.
  39328. * @return {UniformsGroup} A reference to this uniforms group.
  39329. */
  39330. setName( name ) {
  39331. this.name = name;
  39332. return this;
  39333. }
  39334. /**
  39335. * Sets the usage of this uniforms group.
  39336. *
  39337. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39338. * @return {UniformsGroup} A reference to this uniforms group.
  39339. */
  39340. setUsage( value ) {
  39341. this.usage = value;
  39342. return this;
  39343. }
  39344. /**
  39345. * Frees the GPU-related resources allocated by this instance. Call this
  39346. * method whenever this instance is no longer used in your app.
  39347. *
  39348. * @fires Texture#dispose
  39349. */
  39350. dispose() {
  39351. this.dispatchEvent( { type: 'dispose' } );
  39352. }
  39353. /**
  39354. * Copies the values of the given uniforms group to this instance.
  39355. *
  39356. * @param {UniformsGroup} source - The uniforms group to copy.
  39357. * @return {UniformsGroup} A reference to this uniforms group.
  39358. */
  39359. copy( source ) {
  39360. this.name = source.name;
  39361. this.usage = source.usage;
  39362. const uniformsSource = source.uniforms;
  39363. this.uniforms.length = 0;
  39364. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39365. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39366. for ( let j = 0; j < uniforms.length; j ++ ) {
  39367. this.uniforms.push( uniforms[ j ].clone() );
  39368. }
  39369. }
  39370. return this;
  39371. }
  39372. /**
  39373. * Returns a new uniforms group with copied values from this instance.
  39374. *
  39375. * @return {UniformsGroup} A clone of this instance.
  39376. */
  39377. clone() {
  39378. return new this.constructor().copy( this );
  39379. }
  39380. }
  39381. /**
  39382. * An instanced version of an interleaved buffer.
  39383. *
  39384. * @augments InterleavedBuffer
  39385. */
  39386. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39387. /**
  39388. * Constructs a new instanced interleaved buffer.
  39389. *
  39390. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39391. * @param {number} stride - The number of typed-array elements per vertex.
  39392. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39393. */
  39394. constructor( array, stride, meshPerAttribute = 1 ) {
  39395. super( array, stride );
  39396. /**
  39397. * This flag can be used for type testing.
  39398. *
  39399. * @type {boolean}
  39400. * @readonly
  39401. * @default true
  39402. */
  39403. this.isInstancedInterleavedBuffer = true;
  39404. /**
  39405. * Defines how often a value of this buffer attribute should be repeated,
  39406. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39407. *
  39408. * @type {number}
  39409. * @default 1
  39410. */
  39411. this.meshPerAttribute = meshPerAttribute;
  39412. }
  39413. copy( source ) {
  39414. super.copy( source );
  39415. this.meshPerAttribute = source.meshPerAttribute;
  39416. return this;
  39417. }
  39418. clone( data ) {
  39419. const ib = super.clone( data );
  39420. ib.meshPerAttribute = this.meshPerAttribute;
  39421. return ib;
  39422. }
  39423. toJSON( data ) {
  39424. const json = super.toJSON( data );
  39425. json.isInstancedInterleavedBuffer = true;
  39426. json.meshPerAttribute = this.meshPerAttribute;
  39427. return json;
  39428. }
  39429. }
  39430. /**
  39431. * An alternative version of a buffer attribute with more control over the VBO.
  39432. *
  39433. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39434. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39435. *
  39436. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39437. * or even produces the VBOs in question.
  39438. *
  39439. * Notice that this class can only be used with {@link WebGLRenderer}.
  39440. */
  39441. class GLBufferAttribute {
  39442. /**
  39443. * Constructs a new GL buffer attribute.
  39444. *
  39445. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39446. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39447. * @param {number} itemSize - The item size.
  39448. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39449. * @param {number} count - The expected number of vertices in VBO.
  39450. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39451. */
  39452. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39453. /**
  39454. * This flag can be used for type testing.
  39455. *
  39456. * @type {boolean}
  39457. * @readonly
  39458. * @default true
  39459. */
  39460. this.isGLBufferAttribute = true;
  39461. /**
  39462. * The name of the buffer attribute.
  39463. *
  39464. * @type {string}
  39465. */
  39466. this.name = '';
  39467. /**
  39468. * The native WebGL buffer.
  39469. *
  39470. * @type {WebGLBuffer}
  39471. */
  39472. this.buffer = buffer;
  39473. /**
  39474. * The native data type.
  39475. *
  39476. * @type {number}
  39477. */
  39478. this.type = type;
  39479. /**
  39480. * The item size, see {@link BufferAttribute#itemSize}.
  39481. *
  39482. * @type {number}
  39483. */
  39484. this.itemSize = itemSize;
  39485. /**
  39486. * The corresponding size (in bytes) for the given `type` parameter.
  39487. *
  39488. * @type {number}
  39489. */
  39490. this.elementSize = elementSize;
  39491. /**
  39492. * The expected number of vertices in VBO.
  39493. *
  39494. * @type {number}
  39495. */
  39496. this.count = count;
  39497. /**
  39498. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39499. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39500. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39501. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39502. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39503. *
  39504. * @type {boolean}
  39505. */
  39506. this.normalized = normalized;
  39507. /**
  39508. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39509. *
  39510. * @type {number}
  39511. */
  39512. this.version = 0;
  39513. }
  39514. /**
  39515. * Flag to indicate that this attribute has changed and should be re-sent to
  39516. * the GPU. Set this to `true` when you modify the value of the array.
  39517. *
  39518. * @type {number}
  39519. * @default false
  39520. * @param {boolean} value
  39521. */
  39522. set needsUpdate( value ) {
  39523. if ( value === true ) this.version ++;
  39524. }
  39525. /**
  39526. * Sets the given native WebGL buffer.
  39527. *
  39528. * @param {WebGLBuffer} buffer - The buffer to set.
  39529. * @return {BufferAttribute} A reference to this instance.
  39530. */
  39531. setBuffer( buffer ) {
  39532. this.buffer = buffer;
  39533. return this;
  39534. }
  39535. /**
  39536. * Sets the given native data type and element size.
  39537. *
  39538. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39539. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39540. * @return {BufferAttribute} A reference to this instance.
  39541. */
  39542. setType( type, elementSize ) {
  39543. this.type = type;
  39544. this.elementSize = elementSize;
  39545. return this;
  39546. }
  39547. /**
  39548. * Sets the item size.
  39549. *
  39550. * @param {number} itemSize - The item size.
  39551. * @return {BufferAttribute} A reference to this instance.
  39552. */
  39553. setItemSize( itemSize ) {
  39554. this.itemSize = itemSize;
  39555. return this;
  39556. }
  39557. /**
  39558. * Sets the count (the expected number of vertices in VBO).
  39559. *
  39560. * @param {number} count - The count.
  39561. * @return {BufferAttribute} A reference to this instance.
  39562. */
  39563. setCount( count ) {
  39564. this.count = count;
  39565. return this;
  39566. }
  39567. }
  39568. const _matrix = /*@__PURE__*/ new Matrix4();
  39569. /**
  39570. * This class is designed to assist with raycasting. Raycasting is used for
  39571. * mouse picking (working out what objects in the 3d space the mouse is over)
  39572. * amongst other things.
  39573. */
  39574. class Raycaster {
  39575. /**
  39576. * Constructs a new raycaster.
  39577. *
  39578. * @param {Vector3} origin - The origin vector where the ray casts from.
  39579. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39580. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39581. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39582. */
  39583. constructor( origin, direction, near = 0, far = Infinity ) {
  39584. /**
  39585. * The ray used for raycasting.
  39586. *
  39587. * @type {Ray}
  39588. */
  39589. this.ray = new Ray( origin, direction );
  39590. /**
  39591. * All results returned are further away than near. Near can't be negative.
  39592. *
  39593. * @type {number}
  39594. * @default 0
  39595. */
  39596. this.near = near;
  39597. /**
  39598. * All results returned are further away than near. Near can't be negative.
  39599. *
  39600. * @type {number}
  39601. * @default Infinity
  39602. */
  39603. this.far = far;
  39604. /**
  39605. * The camera to use when raycasting against view-dependent objects such as
  39606. * billboarded objects like sprites. This field can be set manually or
  39607. * is set when calling `setFromCamera()`.
  39608. *
  39609. * @type {?Camera}
  39610. * @default null
  39611. */
  39612. this.camera = null;
  39613. /**
  39614. * Allows to selectively ignore 3D objects when performing intersection tests.
  39615. * The following code example ensures that only 3D objects on layer `1` will be
  39616. * honored by raycaster.
  39617. * ```js
  39618. * raycaster.layers.set( 1 );
  39619. * object.layers.enable( 1 );
  39620. * ```
  39621. *
  39622. * @type {Layers}
  39623. */
  39624. this.layers = new Layers();
  39625. /**
  39626. * A parameter object that configures the raycasting. It has the structure:
  39627. *
  39628. * ```
  39629. * {
  39630. * Mesh: {},
  39631. * Line: { threshold: 1 },
  39632. * LOD: {},
  39633. * Points: { threshold: 1 },
  39634. * Sprite: {}
  39635. * }
  39636. * ```
  39637. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39638. *
  39639. * @type {Object}
  39640. */
  39641. this.params = {
  39642. Mesh: {},
  39643. Line: { threshold: 1 },
  39644. LOD: {},
  39645. Points: { threshold: 1 },
  39646. Sprite: {}
  39647. };
  39648. }
  39649. /**
  39650. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39651. *
  39652. * @param {Vector3} origin - The origin vector where the ray casts from.
  39653. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39654. */
  39655. set( origin, direction ) {
  39656. // direction is assumed to be normalized (for accurate distance calculations)
  39657. this.ray.set( origin, direction );
  39658. }
  39659. /**
  39660. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39661. *
  39662. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39663. * X and Y components should be between `-1` and `1`.
  39664. * @param {Camera} camera - The camera from which the ray should originate.
  39665. */
  39666. setFromCamera( coords, camera ) {
  39667. if ( camera.isPerspectiveCamera ) {
  39668. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39669. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39670. this.camera = camera;
  39671. } else if ( camera.isOrthographicCamera ) {
  39672. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39673. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39674. this.camera = camera;
  39675. } else {
  39676. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  39677. }
  39678. }
  39679. /**
  39680. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39681. *
  39682. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39683. * @return {Raycaster} A reference to this raycaster.
  39684. */
  39685. setFromXRController( controller ) {
  39686. _matrix.identity().extractRotation( controller.matrixWorld );
  39687. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39688. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39689. return this;
  39690. }
  39691. /**
  39692. * The intersection point of a raycaster intersection test.
  39693. * @typedef {Object} Raycaster~Intersection
  39694. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39695. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39696. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39697. * @property {Vector3} point - The intersection point, in world coordinates.
  39698. * @property {Object} face - The face that has been intersected.
  39699. * @property {number} faceIndex - The face index.
  39700. * @property {Object3D} object - The 3D object that has been intersected.
  39701. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39702. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39703. * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
  39704. * @property {number} instanceId - The index number of the instance where the ray
  39705. * intersects the {@link InstancedMesh}.
  39706. */
  39707. /**
  39708. * Checks all intersection between the ray and the object with or without the
  39709. * descendants. Intersections are returned sorted by distance, closest first.
  39710. *
  39711. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39712. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39713. * differently to ray casting than lines or points.
  39714. *
  39715. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39716. * to be detected; intersections of the ray passing through the back of a face will not
  39717. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39718. * to `THREE.DoubleSide`.
  39719. *
  39720. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39721. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39722. * Otherwise it only checks intersection with the object.
  39723. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39724. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39725. */
  39726. intersectObject( object, recursive = true, intersects = [] ) {
  39727. intersect( object, this, intersects, recursive );
  39728. intersects.sort( ascSort );
  39729. return intersects;
  39730. }
  39731. /**
  39732. * Checks all intersection between the ray and the objects with or without
  39733. * the descendants. Intersections are returned sorted by distance, closest first.
  39734. *
  39735. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39736. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39737. * Otherwise it only checks intersection with the object.
  39738. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39739. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39740. */
  39741. intersectObjects( objects, recursive = true, intersects = [] ) {
  39742. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39743. intersect( objects[ i ], this, intersects, recursive );
  39744. }
  39745. intersects.sort( ascSort );
  39746. return intersects;
  39747. }
  39748. }
  39749. function ascSort( a, b ) {
  39750. return a.distance - b.distance;
  39751. }
  39752. function intersect( object, raycaster, intersects, recursive ) {
  39753. let propagate = true;
  39754. if ( object.layers.test( raycaster.layers ) ) {
  39755. const result = object.raycast( raycaster, intersects );
  39756. if ( result === false ) propagate = false;
  39757. }
  39758. if ( propagate === true && recursive === true ) {
  39759. const children = object.children;
  39760. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39761. intersect( children[ i ], raycaster, intersects, true );
  39762. }
  39763. }
  39764. }
  39765. /**
  39766. * This class is an alternative to {@link Clock} with a different API design and behavior.
  39767. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  39768. *
  39769. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  39770. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  39771. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  39772. * is inactive (e.g. tab switched or browser hidden).
  39773. *
  39774. * ```js
  39775. * const timer = new Timer();
  39776. * timer.connect( document ); // use Page Visibility API
  39777. * ```
  39778. */
  39779. class Timer {
  39780. /**
  39781. * Constructs a new timer.
  39782. */
  39783. constructor() {
  39784. this._previousTime = 0;
  39785. this._currentTime = 0;
  39786. this._startTime = performance.now();
  39787. this._delta = 0;
  39788. this._elapsed = 0;
  39789. this._timescale = 1;
  39790. this._document = null;
  39791. this._pageVisibilityHandler = null;
  39792. }
  39793. /**
  39794. * Connect the timer to the given document.Calling this method is not mandatory to
  39795. * use the timer but enables the usage of the Page Visibility API to avoid large time
  39796. * delta values.
  39797. *
  39798. * @param {Document} document - The document.
  39799. */
  39800. connect( document ) {
  39801. this._document = document;
  39802. // use Page Visibility API to avoid large time delta values
  39803. if ( document.hidden !== undefined ) {
  39804. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  39805. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  39806. }
  39807. }
  39808. /**
  39809. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  39810. */
  39811. disconnect() {
  39812. if ( this._pageVisibilityHandler !== null ) {
  39813. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  39814. this._pageVisibilityHandler = null;
  39815. }
  39816. this._document = null;
  39817. }
  39818. /**
  39819. * Returns the time delta in seconds.
  39820. *
  39821. * @return {number} The time delta in second.
  39822. */
  39823. getDelta() {
  39824. return this._delta / 1000;
  39825. }
  39826. /**
  39827. * Returns the elapsed time in seconds.
  39828. *
  39829. * @return {number} The elapsed time in second.
  39830. */
  39831. getElapsed() {
  39832. return this._elapsed / 1000;
  39833. }
  39834. /**
  39835. * Returns the timescale.
  39836. *
  39837. * @return {number} The timescale.
  39838. */
  39839. getTimescale() {
  39840. return this._timescale;
  39841. }
  39842. /**
  39843. * Sets the given timescale which scale the time delta computation
  39844. * in `update()`.
  39845. *
  39846. * @param {number} timescale - The timescale to set.
  39847. * @return {Timer} A reference to this timer.
  39848. */
  39849. setTimescale( timescale ) {
  39850. this._timescale = timescale;
  39851. return this;
  39852. }
  39853. /**
  39854. * Resets the time computation for the current simulation step.
  39855. *
  39856. * @return {Timer} A reference to this timer.
  39857. */
  39858. reset() {
  39859. this._currentTime = performance.now() - this._startTime;
  39860. return this;
  39861. }
  39862. /**
  39863. * Can be used to free all internal resources. Usually called when
  39864. * the timer instance isn't required anymore.
  39865. */
  39866. dispose() {
  39867. this.disconnect();
  39868. }
  39869. /**
  39870. * Updates the internal state of the timer. This method should be called
  39871. * once per simulation step and before you perform queries against the timer
  39872. * (e.g. via `getDelta()`).
  39873. *
  39874. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  39875. * from the `requestAnimationFrame` callback argument. If not provided, the current
  39876. * time will be determined with `performance.now`.
  39877. * @return {Timer} A reference to this timer.
  39878. */
  39879. update( timestamp ) {
  39880. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  39881. this._delta = 0;
  39882. } else {
  39883. this._previousTime = this._currentTime;
  39884. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  39885. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  39886. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  39887. }
  39888. return this;
  39889. }
  39890. }
  39891. function handleVisibilityChange() {
  39892. if ( this._document.hidden === false ) this.reset();
  39893. }
  39894. /**
  39895. * This class can be used to represent points in 3D space as
  39896. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  39897. */
  39898. class Spherical {
  39899. /**
  39900. * Constructs a new spherical.
  39901. *
  39902. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39903. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  39904. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  39905. */
  39906. constructor( radius = 1, phi = 0, theta = 0 ) {
  39907. /**
  39908. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39909. *
  39910. * @type {number}
  39911. * @default 1
  39912. */
  39913. this.radius = radius;
  39914. /**
  39915. * The polar angle in radians from the y (up) axis.
  39916. *
  39917. * @type {number}
  39918. * @default 0
  39919. */
  39920. this.phi = phi;
  39921. /**
  39922. * The equator/azimuthal angle in radians around the y (up) axis.
  39923. *
  39924. * @type {number}
  39925. * @default 0
  39926. */
  39927. this.theta = theta;
  39928. }
  39929. /**
  39930. * Sets the spherical components by copying the given values.
  39931. *
  39932. * @param {number} radius - The radius.
  39933. * @param {number} phi - The polar angle.
  39934. * @param {number} theta - The azimuthal angle.
  39935. * @return {Spherical} A reference to this spherical.
  39936. */
  39937. set( radius, phi, theta ) {
  39938. this.radius = radius;
  39939. this.phi = phi;
  39940. this.theta = theta;
  39941. return this;
  39942. }
  39943. /**
  39944. * Copies the values of the given spherical to this instance.
  39945. *
  39946. * @param {Spherical} other - The spherical to copy.
  39947. * @return {Spherical} A reference to this spherical.
  39948. */
  39949. copy( other ) {
  39950. this.radius = other.radius;
  39951. this.phi = other.phi;
  39952. this.theta = other.theta;
  39953. return this;
  39954. }
  39955. /**
  39956. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  39957. * `0.000001`.
  39958. *
  39959. * @return {Spherical} A reference to this spherical.
  39960. */
  39961. makeSafe() {
  39962. const EPS = 0.000001;
  39963. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  39964. return this;
  39965. }
  39966. /**
  39967. * Sets the spherical components from the given vector which is assumed to hold
  39968. * Cartesian coordinates.
  39969. *
  39970. * @param {Vector3} v - The vector to set.
  39971. * @return {Spherical} A reference to this spherical.
  39972. */
  39973. setFromVector3( v ) {
  39974. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39975. }
  39976. /**
  39977. * Sets the spherical components from the given Cartesian coordinates.
  39978. *
  39979. * @param {number} x - The x value.
  39980. * @param {number} y - The y value.
  39981. * @param {number} z - The z value.
  39982. * @return {Spherical} A reference to this spherical.
  39983. */
  39984. setFromCartesianCoords( x, y, z ) {
  39985. this.radius = Math.sqrt( x * x + y * y + z * z );
  39986. if ( this.radius === 0 ) {
  39987. this.theta = 0;
  39988. this.phi = 0;
  39989. } else {
  39990. this.theta = Math.atan2( x, z );
  39991. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  39992. }
  39993. return this;
  39994. }
  39995. /**
  39996. * Returns a new spherical with copied values from this instance.
  39997. *
  39998. * @return {Spherical} A clone of this instance.
  39999. */
  40000. clone() {
  40001. return new this.constructor().copy( this );
  40002. }
  40003. }
  40004. /**
  40005. * This class can be used to represent points in 3D space as
  40006. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  40007. */
  40008. class Cylindrical {
  40009. /**
  40010. * Constructs a new cylindrical.
  40011. *
  40012. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40013. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40014. * @param {number} [y=0] - The height above the x-z plane.
  40015. */
  40016. constructor( radius = 1, theta = 0, y = 0 ) {
  40017. /**
  40018. * The distance from the origin to a point in the x-z plane.
  40019. *
  40020. * @type {number}
  40021. * @default 1
  40022. */
  40023. this.radius = radius;
  40024. /**
  40025. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40026. *
  40027. * @type {number}
  40028. * @default 0
  40029. */
  40030. this.theta = theta;
  40031. /**
  40032. * The height above the x-z plane.
  40033. *
  40034. * @type {number}
  40035. * @default 0
  40036. */
  40037. this.y = y;
  40038. }
  40039. /**
  40040. * Sets the cylindrical components by copying the given values.
  40041. *
  40042. * @param {number} radius - The radius.
  40043. * @param {number} theta - The theta angle.
  40044. * @param {number} y - The height value.
  40045. * @return {Cylindrical} A reference to this cylindrical.
  40046. */
  40047. set( radius, theta, y ) {
  40048. this.radius = radius;
  40049. this.theta = theta;
  40050. this.y = y;
  40051. return this;
  40052. }
  40053. /**
  40054. * Copies the values of the given cylindrical to this instance.
  40055. *
  40056. * @param {Cylindrical} other - The cylindrical to copy.
  40057. * @return {Cylindrical} A reference to this cylindrical.
  40058. */
  40059. copy( other ) {
  40060. this.radius = other.radius;
  40061. this.theta = other.theta;
  40062. this.y = other.y;
  40063. return this;
  40064. }
  40065. /**
  40066. * Sets the cylindrical components from the given vector which is assumed to hold
  40067. * Cartesian coordinates.
  40068. *
  40069. * @param {Vector3} v - The vector to set.
  40070. * @return {Cylindrical} A reference to this cylindrical.
  40071. */
  40072. setFromVector3( v ) {
  40073. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40074. }
  40075. /**
  40076. * Sets the cylindrical components from the given Cartesian coordinates.
  40077. *
  40078. * @param {number} x - The x value.
  40079. * @param {number} y - The x value.
  40080. * @param {number} z - The x value.
  40081. * @return {Cylindrical} A reference to this cylindrical.
  40082. */
  40083. setFromCartesianCoords( x, y, z ) {
  40084. this.radius = Math.sqrt( x * x + z * z );
  40085. this.theta = Math.atan2( x, z );
  40086. this.y = y;
  40087. return this;
  40088. }
  40089. /**
  40090. * Returns a new cylindrical with copied values from this instance.
  40091. *
  40092. * @return {Cylindrical} A clone of this instance.
  40093. */
  40094. clone() {
  40095. return new this.constructor().copy( this );
  40096. }
  40097. }
  40098. /**
  40099. * Represents a 2x2 matrix.
  40100. *
  40101. * A Note on Row-Major and Column-Major Ordering:
  40102. *
  40103. * The constructor and {@link Matrix2#set} method take arguments in
  40104. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  40105. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40106. * This means that calling:
  40107. * ```js
  40108. * const m = new THREE.Matrix2();
  40109. * m.set( 11, 12,
  40110. * 21, 22 );
  40111. * ```
  40112. * will result in the elements array containing:
  40113. * ```js
  40114. * m.elements = [ 11, 21,
  40115. * 12, 22 ];
  40116. * ```
  40117. * and internally all calculations are performed using column-major ordering.
  40118. * However, as the actual ordering makes no difference mathematically and
  40119. * most people are used to thinking about matrices in row-major order, the
  40120. * three.js documentation shows matrices in row-major order. Just bear in
  40121. * mind that if you are reading the source code, you'll have to take the
  40122. * transpose of any matrices outlined here to make sense of the calculations.
  40123. */
  40124. class Matrix2 {
  40125. /**
  40126. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40127. * in row-major order. If no arguments are provided, the constructor
  40128. * initializes the matrix as an identity matrix.
  40129. *
  40130. * @param {number} [n11] - 1-1 matrix element.
  40131. * @param {number} [n12] - 1-2 matrix element.
  40132. * @param {number} [n21] - 2-1 matrix element.
  40133. * @param {number} [n22] - 2-2 matrix element.
  40134. */
  40135. constructor( n11, n12, n21, n22 ) {
  40136. /**
  40137. * This flag can be used for type testing.
  40138. *
  40139. * @type {boolean}
  40140. * @readonly
  40141. * @default true
  40142. */
  40143. Matrix2.prototype.isMatrix2 = true;
  40144. /**
  40145. * A column-major list of matrix values.
  40146. *
  40147. * @type {Array<number>}
  40148. */
  40149. this.elements = [
  40150. 1, 0,
  40151. 0, 1,
  40152. ];
  40153. if ( n11 !== undefined ) {
  40154. this.set( n11, n12, n21, n22 );
  40155. }
  40156. }
  40157. /**
  40158. * Sets this matrix to the 2x2 identity matrix.
  40159. *
  40160. * @return {Matrix2} A reference to this matrix.
  40161. */
  40162. identity() {
  40163. this.set(
  40164. 1, 0,
  40165. 0, 1,
  40166. );
  40167. return this;
  40168. }
  40169. /**
  40170. * Sets the elements of the matrix from the given array.
  40171. *
  40172. * @param {Array<number>} array - The matrix elements in column-major order.
  40173. * @param {number} [offset=0] - Index of the first element in the array.
  40174. * @return {Matrix2} A reference to this matrix.
  40175. */
  40176. fromArray( array, offset = 0 ) {
  40177. for ( let i = 0; i < 4; i ++ ) {
  40178. this.elements[ i ] = array[ i + offset ];
  40179. }
  40180. return this;
  40181. }
  40182. /**
  40183. * Sets the elements of the matrix.The arguments are supposed to be
  40184. * in row-major order.
  40185. *
  40186. * @param {number} n11 - 1-1 matrix element.
  40187. * @param {number} n12 - 1-2 matrix element.
  40188. * @param {number} n21 - 2-1 matrix element.
  40189. * @param {number} n22 - 2-2 matrix element.
  40190. * @return {Matrix2} A reference to this matrix.
  40191. */
  40192. set( n11, n12, n21, n22 ) {
  40193. const te = this.elements;
  40194. te[ 0 ] = n11; te[ 2 ] = n12;
  40195. te[ 1 ] = n21; te[ 3 ] = n22;
  40196. return this;
  40197. }
  40198. }
  40199. const _vector$4 = /*@__PURE__*/ new Vector2();
  40200. /**
  40201. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40202. */
  40203. class Box2 {
  40204. /**
  40205. * Constructs a new bounding box.
  40206. *
  40207. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40208. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40209. */
  40210. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40211. /**
  40212. * This flag can be used for type testing.
  40213. *
  40214. * @type {boolean}
  40215. * @readonly
  40216. * @default true
  40217. */
  40218. this.isBox2 = true;
  40219. /**
  40220. * The lower boundary of the box.
  40221. *
  40222. * @type {Vector2}
  40223. */
  40224. this.min = min;
  40225. /**
  40226. * The upper boundary of the box.
  40227. *
  40228. * @type {Vector2}
  40229. */
  40230. this.max = max;
  40231. }
  40232. /**
  40233. * Sets the lower and upper boundaries of this box.
  40234. * Please note that this method only copies the values from the given objects.
  40235. *
  40236. * @param {Vector2} min - The lower boundary of the box.
  40237. * @param {Vector2} max - The upper boundary of the box.
  40238. * @return {Box2} A reference to this bounding box.
  40239. */
  40240. set( min, max ) {
  40241. this.min.copy( min );
  40242. this.max.copy( max );
  40243. return this;
  40244. }
  40245. /**
  40246. * Sets the upper and lower bounds of this box so it encloses the position data
  40247. * in the given array.
  40248. *
  40249. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40250. * @return {Box2} A reference to this bounding box.
  40251. */
  40252. setFromPoints( points ) {
  40253. this.makeEmpty();
  40254. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40255. this.expandByPoint( points[ i ] );
  40256. }
  40257. return this;
  40258. }
  40259. /**
  40260. * Centers this box on the given center vector and sets this box's width, height and
  40261. * depth to the given size values.
  40262. *
  40263. * @param {Vector2} center - The center of the box.
  40264. * @param {Vector2} size - The x and y dimensions of the box.
  40265. * @return {Box2} A reference to this bounding box.
  40266. */
  40267. setFromCenterAndSize( center, size ) {
  40268. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40269. this.min.copy( center ).sub( halfSize );
  40270. this.max.copy( center ).add( halfSize );
  40271. return this;
  40272. }
  40273. /**
  40274. * Returns a new box with copied values from this instance.
  40275. *
  40276. * @return {Box2} A clone of this instance.
  40277. */
  40278. clone() {
  40279. return new this.constructor().copy( this );
  40280. }
  40281. /**
  40282. * Copies the values of the given box to this instance.
  40283. *
  40284. * @param {Box2} box - The box to copy.
  40285. * @return {Box2} A reference to this bounding box.
  40286. */
  40287. copy( box ) {
  40288. this.min.copy( box.min );
  40289. this.max.copy( box.max );
  40290. return this;
  40291. }
  40292. /**
  40293. * Makes this box empty which means in encloses a zero space in 2D.
  40294. *
  40295. * @return {Box2} A reference to this bounding box.
  40296. */
  40297. makeEmpty() {
  40298. this.min.x = this.min.y = + Infinity;
  40299. this.max.x = this.max.y = - Infinity;
  40300. return this;
  40301. }
  40302. /**
  40303. * Returns true if this box includes zero points within its bounds.
  40304. * Note that a box with equal lower and upper bounds still includes one
  40305. * point, the one both bounds share.
  40306. *
  40307. * @return {boolean} Whether this box is empty or not.
  40308. */
  40309. isEmpty() {
  40310. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40311. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40312. }
  40313. /**
  40314. * Returns the center point of this box.
  40315. *
  40316. * @param {Vector2} target - The target vector that is used to store the method's result.
  40317. * @return {Vector2} The center point.
  40318. */
  40319. getCenter( target ) {
  40320. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40321. }
  40322. /**
  40323. * Returns the dimensions of this box.
  40324. *
  40325. * @param {Vector2} target - The target vector that is used to store the method's result.
  40326. * @return {Vector2} The size.
  40327. */
  40328. getSize( target ) {
  40329. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40330. }
  40331. /**
  40332. * Expands the boundaries of this box to include the given point.
  40333. *
  40334. * @param {Vector2} point - The point that should be included by the bounding box.
  40335. * @return {Box2} A reference to this bounding box.
  40336. */
  40337. expandByPoint( point ) {
  40338. this.min.min( point );
  40339. this.max.max( point );
  40340. return this;
  40341. }
  40342. /**
  40343. * Expands this box equilaterally by the given vector. The width of this
  40344. * box will be expanded by the x component of the vector in both
  40345. * directions. The height of this box will be expanded by the y component of
  40346. * the vector in both directions.
  40347. *
  40348. * @param {Vector2} vector - The vector that should expand the bounding box.
  40349. * @return {Box2} A reference to this bounding box.
  40350. */
  40351. expandByVector( vector ) {
  40352. this.min.sub( vector );
  40353. this.max.add( vector );
  40354. return this;
  40355. }
  40356. /**
  40357. * Expands each dimension of the box by the given scalar. If negative, the
  40358. * dimensions of the box will be contracted.
  40359. *
  40360. * @param {number} scalar - The scalar value that should expand the bounding box.
  40361. * @return {Box2} A reference to this bounding box.
  40362. */
  40363. expandByScalar( scalar ) {
  40364. this.min.addScalar( - scalar );
  40365. this.max.addScalar( scalar );
  40366. return this;
  40367. }
  40368. /**
  40369. * Returns `true` if the given point lies within or on the boundaries of this box.
  40370. *
  40371. * @param {Vector2} point - The point to test.
  40372. * @return {boolean} Whether the bounding box contains the given point or not.
  40373. */
  40374. containsPoint( point ) {
  40375. return point.x >= this.min.x && point.x <= this.max.x &&
  40376. point.y >= this.min.y && point.y <= this.max.y;
  40377. }
  40378. /**
  40379. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40380. * If this box and the given one are identical, this function also returns `true`.
  40381. *
  40382. * @param {Box2} box - The bounding box to test.
  40383. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40384. */
  40385. containsBox( box ) {
  40386. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40387. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40388. }
  40389. /**
  40390. * Returns a point as a proportion of this box's width and height.
  40391. *
  40392. * @param {Vector2} point - A point in 2D space.
  40393. * @param {Vector2} target - The target vector that is used to store the method's result.
  40394. * @return {Vector2} A point as a proportion of this box's width and height.
  40395. */
  40396. getParameter( point, target ) {
  40397. // This can potentially have a divide by zero if the box
  40398. // has a size dimension of 0.
  40399. return target.set(
  40400. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40401. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40402. );
  40403. }
  40404. /**
  40405. * Returns `true` if the given bounding box intersects with this bounding box.
  40406. *
  40407. * @param {Box2} box - The bounding box to test.
  40408. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40409. */
  40410. intersectsBox( box ) {
  40411. // using 4 splitting planes to rule out intersections
  40412. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40413. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40414. }
  40415. /**
  40416. * Clamps the given point within the bounds of this box.
  40417. *
  40418. * @param {Vector2} point - The point to clamp.
  40419. * @param {Vector2} target - The target vector that is used to store the method's result.
  40420. * @return {Vector2} The clamped point.
  40421. */
  40422. clampPoint( point, target ) {
  40423. return target.copy( point ).clamp( this.min, this.max );
  40424. }
  40425. /**
  40426. * Returns the euclidean distance from any edge of this box to the specified point. If
  40427. * the given point lies inside of this box, the distance will be `0`.
  40428. *
  40429. * @param {Vector2} point - The point to compute the distance to.
  40430. * @return {number} The euclidean distance.
  40431. */
  40432. distanceToPoint( point ) {
  40433. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40434. }
  40435. /**
  40436. * Computes the intersection of this bounding box and the given one, setting the upper
  40437. * bound of this box to the lesser of the two boxes' upper bounds and the
  40438. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40439. * there's no overlap, makes this box empty.
  40440. *
  40441. * @param {Box2} box - The bounding box to intersect with.
  40442. * @return {Box2} A reference to this bounding box.
  40443. */
  40444. intersect( box ) {
  40445. this.min.max( box.min );
  40446. this.max.min( box.max );
  40447. if ( this.isEmpty() ) this.makeEmpty();
  40448. return this;
  40449. }
  40450. /**
  40451. * Computes the union of this box and another and the given one, setting the upper
  40452. * bound of this box to the greater of the two boxes' upper bounds and the
  40453. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40454. *
  40455. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40456. * @return {Box2} A reference to this bounding box.
  40457. */
  40458. union( box ) {
  40459. this.min.min( box.min );
  40460. this.max.max( box.max );
  40461. return this;
  40462. }
  40463. /**
  40464. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40465. * effectively moving it in 2D space.
  40466. *
  40467. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40468. * @return {Box2} A reference to this bounding box.
  40469. */
  40470. translate( offset ) {
  40471. this.min.add( offset );
  40472. this.max.add( offset );
  40473. return this;
  40474. }
  40475. /**
  40476. * Returns `true` if this bounding box is equal with the given one.
  40477. *
  40478. * @param {Box2} box - The box to test for equality.
  40479. * @return {boolean} Whether this bounding box is equal with the given one.
  40480. */
  40481. equals( box ) {
  40482. return box.min.equals( this.min ) && box.max.equals( this.max );
  40483. }
  40484. }
  40485. const _startP = /*@__PURE__*/ new Vector3();
  40486. const _startEnd = /*@__PURE__*/ new Vector3();
  40487. const _d1 = /*@__PURE__*/ new Vector3();
  40488. const _d2 = /*@__PURE__*/ new Vector3();
  40489. const _r = /*@__PURE__*/ new Vector3();
  40490. const _c1 = /*@__PURE__*/ new Vector3();
  40491. const _c2 = /*@__PURE__*/ new Vector3();
  40492. /**
  40493. * An analytical line segment in 3D space represented by a start and end point.
  40494. */
  40495. class Line3 {
  40496. /**
  40497. * Constructs a new line segment.
  40498. *
  40499. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40500. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40501. */
  40502. constructor( start = new Vector3(), end = new Vector3() ) {
  40503. /**
  40504. * Start of the line segment.
  40505. *
  40506. * @type {Vector3}
  40507. */
  40508. this.start = start;
  40509. /**
  40510. * End of the line segment.
  40511. *
  40512. * @type {Vector3}
  40513. */
  40514. this.end = end;
  40515. }
  40516. /**
  40517. * Sets the start and end values by copying the given vectors.
  40518. *
  40519. * @param {Vector3} start - The start point.
  40520. * @param {Vector3} end - The end point.
  40521. * @return {Line3} A reference to this line segment.
  40522. */
  40523. set( start, end ) {
  40524. this.start.copy( start );
  40525. this.end.copy( end );
  40526. return this;
  40527. }
  40528. /**
  40529. * Copies the values of the given line segment to this instance.
  40530. *
  40531. * @param {Line3} line - The line segment to copy.
  40532. * @return {Line3} A reference to this line segment.
  40533. */
  40534. copy( line ) {
  40535. this.start.copy( line.start );
  40536. this.end.copy( line.end );
  40537. return this;
  40538. }
  40539. /**
  40540. * Returns the center of the line segment.
  40541. *
  40542. * @param {Vector3} target - The target vector that is used to store the method's result.
  40543. * @return {Vector3} The center point.
  40544. */
  40545. getCenter( target ) {
  40546. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40547. }
  40548. /**
  40549. * Returns the delta vector of the line segment's start and end point.
  40550. *
  40551. * @param {Vector3} target - The target vector that is used to store the method's result.
  40552. * @return {Vector3} The delta vector.
  40553. */
  40554. delta( target ) {
  40555. return target.subVectors( this.end, this.start );
  40556. }
  40557. /**
  40558. * Returns the squared Euclidean distance between the line' start and end point.
  40559. *
  40560. * @return {number} The squared Euclidean distance.
  40561. */
  40562. distanceSq() {
  40563. return this.start.distanceToSquared( this.end );
  40564. }
  40565. /**
  40566. * Returns the Euclidean distance between the line' start and end point.
  40567. *
  40568. * @return {number} The Euclidean distance.
  40569. */
  40570. distance() {
  40571. return this.start.distanceTo( this.end );
  40572. }
  40573. /**
  40574. * Returns a vector at a certain position along the line segment.
  40575. *
  40576. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40577. * @param {Vector3} target - The target vector that is used to store the method's result.
  40578. * @return {Vector3} The delta vector.
  40579. */
  40580. at( t, target ) {
  40581. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40582. }
  40583. /**
  40584. * Returns a point parameter based on the closest point as projected on the line segment.
  40585. *
  40586. * @param {Vector3} point - The point for which to return a point parameter.
  40587. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40588. * @return {number} The point parameter.
  40589. */
  40590. closestPointToPointParameter( point, clampToLine ) {
  40591. _startP.subVectors( point, this.start );
  40592. _startEnd.subVectors( this.end, this.start );
  40593. const startEnd2 = _startEnd.dot( _startEnd );
  40594. const startEnd_startP = _startEnd.dot( _startP );
  40595. let t = startEnd_startP / startEnd2;
  40596. if ( clampToLine ) {
  40597. t = clamp( t, 0, 1 );
  40598. }
  40599. return t;
  40600. }
  40601. /**
  40602. * Returns the closest point on the line for a given point.
  40603. *
  40604. * @param {Vector3} point - The point to compute the closest point on the line for.
  40605. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40606. * @param {Vector3} target - The target vector that is used to store the method's result.
  40607. * @return {Vector3} The closest point on the line.
  40608. */
  40609. closestPointToPoint( point, clampToLine, target ) {
  40610. const t = this.closestPointToPointParameter( point, clampToLine );
  40611. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40612. }
  40613. /**
  40614. * Returns the closest squared distance between this line segment and the given one.
  40615. *
  40616. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40617. * @param {Vector3} [c1] - The closest point on this line segment.
  40618. * @param {Vector3} [c2] - The closest point on the given line segment.
  40619. * @return {number} The squared distance between this line segment and the given one.
  40620. */
  40621. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40622. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40623. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40624. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40625. // distance between between S1(s) and S2(t)
  40626. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40627. let s, t;
  40628. const p1 = this.start;
  40629. const p2 = line.start;
  40630. const q1 = this.end;
  40631. const q2 = line.end;
  40632. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40633. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40634. _r.subVectors( p1, p2 );
  40635. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40636. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40637. const f = _d2.dot( _r );
  40638. // Check if either or both segments degenerate into points
  40639. if ( a <= EPSILON && e <= EPSILON ) {
  40640. // Both segments degenerate into points
  40641. c1.copy( p1 );
  40642. c2.copy( p2 );
  40643. c1.sub( c2 );
  40644. return c1.dot( c1 );
  40645. }
  40646. if ( a <= EPSILON ) {
  40647. // First segment degenerates into a point
  40648. s = 0;
  40649. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40650. t = clamp( t, 0, 1 );
  40651. } else {
  40652. const c = _d1.dot( _r );
  40653. if ( e <= EPSILON ) {
  40654. // Second segment degenerates into a point
  40655. t = 0;
  40656. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40657. } else {
  40658. // The general nondegenerate case starts here
  40659. const b = _d1.dot( _d2 );
  40660. const denom = a * e - b * b; // Always nonnegative
  40661. // If segments not parallel, compute closest point on L1 to L2 and
  40662. // clamp to segment S1. Else pick arbitrary s (here 0)
  40663. if ( denom !== 0 ) {
  40664. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40665. } else {
  40666. s = 0;
  40667. }
  40668. // Compute point on L2 closest to S1(s) using
  40669. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40670. t = ( b * s + f ) / e;
  40671. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40672. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40673. // and clamp s to [0, 1]
  40674. if ( t < 0 ) {
  40675. t = 0.;
  40676. s = clamp( - c / a, 0, 1 );
  40677. } else if ( t > 1 ) {
  40678. t = 1;
  40679. s = clamp( ( b - c ) / a, 0, 1 );
  40680. }
  40681. }
  40682. }
  40683. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40684. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40685. c1.sub( c2 );
  40686. return c1.dot( c1 );
  40687. }
  40688. /**
  40689. * Applies a 4x4 transformation matrix to this line segment.
  40690. *
  40691. * @param {Matrix4} matrix - The transformation matrix.
  40692. * @return {Line3} A reference to this line segment.
  40693. */
  40694. applyMatrix4( matrix ) {
  40695. this.start.applyMatrix4( matrix );
  40696. this.end.applyMatrix4( matrix );
  40697. return this;
  40698. }
  40699. /**
  40700. * Returns `true` if this line segment is equal with the given one.
  40701. *
  40702. * @param {Line3} line - The line segment to test for equality.
  40703. * @return {boolean} Whether this line segment is equal with the given one.
  40704. */
  40705. equals( line ) {
  40706. return line.start.equals( this.start ) && line.end.equals( this.end );
  40707. }
  40708. /**
  40709. * Returns a new line segment with copied values from this instance.
  40710. *
  40711. * @return {Line3} A clone of this instance.
  40712. */
  40713. clone() {
  40714. return new this.constructor().copy( this );
  40715. }
  40716. }
  40717. const _vector$3 = /*@__PURE__*/ new Vector3();
  40718. /**
  40719. * This displays a cone shaped helper object for a {@link SpotLight}.
  40720. *
  40721. * ```js
  40722. * const spotLight = new THREE.SpotLight( 0xffffff );
  40723. * spotLight.position.set( 10, 10, 10 );
  40724. * scene.add( spotLight );
  40725. *
  40726. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40727. * scene.add( spotLightHelper );
  40728. * ```
  40729. *
  40730. * @augments Object3D
  40731. */
  40732. class SpotLightHelper extends Object3D {
  40733. /**
  40734. * Constructs a new spot light helper.
  40735. *
  40736. * @param {HemisphereLight} light - The light to be visualized.
  40737. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40738. * the color of the light.
  40739. */
  40740. constructor( light, color ) {
  40741. super();
  40742. /**
  40743. * The light being visualized.
  40744. *
  40745. * @type {SpotLight}
  40746. */
  40747. this.light = light;
  40748. this.matrixAutoUpdate = false;
  40749. /**
  40750. * The color parameter passed in the constructor.
  40751. * If not set, the helper will take the color of the light.
  40752. *
  40753. * @type {number|Color|string}
  40754. */
  40755. this.color = color;
  40756. this.type = 'SpotLightHelper';
  40757. const geometry = new BufferGeometry();
  40758. const positions = [
  40759. 0, 0, 0, 0, 0, 1,
  40760. 0, 0, 0, 1, 0, 1,
  40761. 0, 0, 0, -1, 0, 1,
  40762. 0, 0, 0, 0, 1, 1,
  40763. 0, 0, 0, 0, -1, 1
  40764. ];
  40765. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40766. const p1 = ( i / l ) * Math.PI * 2;
  40767. const p2 = ( j / l ) * Math.PI * 2;
  40768. positions.push(
  40769. Math.cos( p1 ), Math.sin( p1 ), 1,
  40770. Math.cos( p2 ), Math.sin( p2 ), 1
  40771. );
  40772. }
  40773. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40774. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40775. this.cone = new LineSegments( geometry, material );
  40776. this.add( this.cone );
  40777. this.update();
  40778. }
  40779. /**
  40780. * Frees the GPU-related resources allocated by this instance. Call this
  40781. * method whenever this instance is no longer used in your app.
  40782. */
  40783. dispose() {
  40784. this.cone.geometry.dispose();
  40785. this.cone.material.dispose();
  40786. }
  40787. /**
  40788. * Updates the helper to match the position and direction of the
  40789. * light being visualized.
  40790. */
  40791. update() {
  40792. this.light.updateWorldMatrix( true, false );
  40793. this.light.target.updateWorldMatrix( true, false );
  40794. // update the local matrix based on the parent and light target transforms
  40795. if ( this.parent ) {
  40796. this.parent.updateWorldMatrix( true );
  40797. this.matrix
  40798. .copy( this.parent.matrixWorld )
  40799. .invert()
  40800. .multiply( this.light.matrixWorld );
  40801. } else {
  40802. this.matrix.copy( this.light.matrixWorld );
  40803. }
  40804. this.matrixWorld.copy( this.light.matrixWorld );
  40805. const coneLength = this.light.distance ? this.light.distance : 1000;
  40806. const coneWidth = coneLength * Math.tan( this.light.angle );
  40807. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  40808. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  40809. this.cone.lookAt( _vector$3 );
  40810. if ( this.color !== undefined ) {
  40811. this.cone.material.color.set( this.color );
  40812. } else {
  40813. this.cone.material.color.copy( this.light.color );
  40814. }
  40815. }
  40816. }
  40817. const _vector$2 = /*@__PURE__*/ new Vector3();
  40818. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  40819. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  40820. /**
  40821. * A helper object to assist with visualizing a {@link Skeleton}.
  40822. *
  40823. * ```js
  40824. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  40825. * scene.add( helper );
  40826. * ```
  40827. *
  40828. * @augments LineSegments
  40829. */
  40830. class SkeletonHelper extends LineSegments {
  40831. /**
  40832. * Constructs a new skeleton helper.
  40833. *
  40834. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  40835. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  40836. */
  40837. constructor( object ) {
  40838. const bones = getBoneList( object );
  40839. const geometry = new BufferGeometry();
  40840. const vertices = [];
  40841. const colors = [];
  40842. for ( let i = 0; i < bones.length; i ++ ) {
  40843. const bone = bones[ i ];
  40844. if ( bone.parent && bone.parent.isBone ) {
  40845. vertices.push( 0, 0, 0 );
  40846. vertices.push( 0, 0, 0 );
  40847. colors.push( 0, 0, 0 );
  40848. colors.push( 0, 0, 0 );
  40849. }
  40850. }
  40851. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40852. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40853. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  40854. super( geometry, material );
  40855. /**
  40856. * This flag can be used for type testing.
  40857. *
  40858. * @type {boolean}
  40859. * @readonly
  40860. * @default true
  40861. */
  40862. this.isSkeletonHelper = true;
  40863. this.type = 'SkeletonHelper';
  40864. /**
  40865. * The object being visualized.
  40866. *
  40867. * @type {Object3D}
  40868. */
  40869. this.root = object;
  40870. /**
  40871. * The list of bones that the helper visualizes.
  40872. *
  40873. * @type {Array<Bone>}
  40874. */
  40875. this.bones = bones;
  40876. this.matrix = object.matrixWorld;
  40877. this.matrixAutoUpdate = false;
  40878. // colors
  40879. const color1 = new Color( 0x0000ff );
  40880. const color2 = new Color( 0x00ff00 );
  40881. this.setColors( color1, color2 );
  40882. }
  40883. updateMatrixWorld( force ) {
  40884. const bones = this.bones;
  40885. const geometry = this.geometry;
  40886. const position = geometry.getAttribute( 'position' );
  40887. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  40888. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  40889. const bone = bones[ i ];
  40890. if ( bone.parent && bone.parent.isBone ) {
  40891. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  40892. _vector$2.setFromMatrixPosition( _boneMatrix );
  40893. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  40894. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  40895. _vector$2.setFromMatrixPosition( _boneMatrix );
  40896. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  40897. j += 2;
  40898. }
  40899. }
  40900. geometry.getAttribute( 'position' ).needsUpdate = true;
  40901. super.updateMatrixWorld( force );
  40902. }
  40903. /**
  40904. * Defines the colors of the helper.
  40905. *
  40906. * @param {Color} color1 - The first line color for each bone.
  40907. * @param {Color} color2 - The second line color for each bone.
  40908. * @return {SkeletonHelper} A reference to this helper.
  40909. */
  40910. setColors( color1, color2 ) {
  40911. const geometry = this.geometry;
  40912. const colorAttribute = geometry.getAttribute( 'color' );
  40913. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  40914. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  40915. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  40916. }
  40917. colorAttribute.needsUpdate = true;
  40918. return this;
  40919. }
  40920. /**
  40921. * Frees the GPU-related resources allocated by this instance. Call this
  40922. * method whenever this instance is no longer used in your app.
  40923. */
  40924. dispose() {
  40925. this.geometry.dispose();
  40926. this.material.dispose();
  40927. }
  40928. }
  40929. function getBoneList( object ) {
  40930. const boneList = [];
  40931. if ( object.isBone === true ) {
  40932. boneList.push( object );
  40933. }
  40934. for ( let i = 0; i < object.children.length; i ++ ) {
  40935. boneList.push( ...getBoneList( object.children[ i ] ) );
  40936. }
  40937. return boneList;
  40938. }
  40939. /**
  40940. * This displays a helper object consisting of a spherical mesh for
  40941. * visualizing an instance of {@link PointLight}.
  40942. *
  40943. * ```js
  40944. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  40945. * pointLight.position.set( 10, 10, 10 );
  40946. * scene.add( pointLight );
  40947. *
  40948. * const sphereSize = 1;
  40949. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  40950. * scene.add( pointLightHelper );
  40951. * ```
  40952. *
  40953. * @augments Mesh
  40954. */
  40955. class PointLightHelper extends Mesh {
  40956. /**
  40957. * Constructs a new point light helper.
  40958. *
  40959. * @param {PointLight} light - The light to be visualized.
  40960. * @param {number} [sphereSize=1] - The size of the sphere helper.
  40961. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40962. * the color of the light.
  40963. */
  40964. constructor( light, sphereSize, color ) {
  40965. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  40966. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40967. super( geometry, material );
  40968. /**
  40969. * The light being visualized.
  40970. *
  40971. * @type {HemisphereLight}
  40972. */
  40973. this.light = light;
  40974. /**
  40975. * The color parameter passed in the constructor.
  40976. * If not set, the helper will take the color of the light.
  40977. *
  40978. * @type {number|Color|string}
  40979. */
  40980. this.color = color;
  40981. this.type = 'PointLightHelper';
  40982. this.matrix = this.light.matrixWorld;
  40983. this.matrixAutoUpdate = false;
  40984. this.update();
  40985. /*
  40986. // TODO: delete this comment?
  40987. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  40988. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  40989. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  40990. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  40991. const d = light.distance;
  40992. if ( d === 0.0 ) {
  40993. this.lightDistance.visible = false;
  40994. } else {
  40995. this.lightDistance.scale.set( d, d, d );
  40996. }
  40997. this.add( this.lightDistance );
  40998. */
  40999. }
  41000. /**
  41001. * Frees the GPU-related resources allocated by this instance. Call this
  41002. * method whenever this instance is no longer used in your app.
  41003. */
  41004. dispose() {
  41005. this.geometry.dispose();
  41006. this.material.dispose();
  41007. }
  41008. /**
  41009. * Updates the helper to match the position of the
  41010. * light being visualized.
  41011. */
  41012. update() {
  41013. this.light.updateWorldMatrix( true, false );
  41014. if ( this.color !== undefined ) {
  41015. this.material.color.set( this.color );
  41016. } else {
  41017. this.material.color.copy( this.light.color );
  41018. }
  41019. /*
  41020. const d = this.light.distance;
  41021. if ( d === 0.0 ) {
  41022. this.lightDistance.visible = false;
  41023. } else {
  41024. this.lightDistance.visible = true;
  41025. this.lightDistance.scale.set( d, d, d );
  41026. }
  41027. */
  41028. }
  41029. }
  41030. const _vector$1 = /*@__PURE__*/ new Vector3();
  41031. const _color1 = /*@__PURE__*/ new Color();
  41032. const _color2 = /*@__PURE__*/ new Color();
  41033. /**
  41034. * Creates a visual aid consisting of a spherical mesh for a
  41035. * given {@link HemisphereLight}.
  41036. *
  41037. * ```js
  41038. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41039. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41040. * scene.add( helper );
  41041. * ```
  41042. *
  41043. * @augments Object3D
  41044. */
  41045. class HemisphereLightHelper extends Object3D {
  41046. /**
  41047. * Constructs a new hemisphere light helper.
  41048. *
  41049. * @param {HemisphereLight} light - The light to be visualized.
  41050. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41051. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41052. * the color of the light.
  41053. */
  41054. constructor( light, size, color ) {
  41055. super();
  41056. /**
  41057. * The light being visualized.
  41058. *
  41059. * @type {HemisphereLight}
  41060. */
  41061. this.light = light;
  41062. this.matrix = light.matrixWorld;
  41063. this.matrixAutoUpdate = false;
  41064. /**
  41065. * The color parameter passed in the constructor.
  41066. * If not set, the helper will take the color of the light.
  41067. *
  41068. * @type {number|Color|string}
  41069. */
  41070. this.color = color;
  41071. this.type = 'HemisphereLightHelper';
  41072. const geometry = new OctahedronGeometry( size );
  41073. geometry.rotateY( Math.PI * 0.5 );
  41074. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41075. if ( this.color === undefined ) this.material.vertexColors = true;
  41076. const position = geometry.getAttribute( 'position' );
  41077. const colors = new Float32Array( position.count * 3 );
  41078. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41079. this.add( new Mesh( geometry, this.material ) );
  41080. this.update();
  41081. }
  41082. /**
  41083. * Frees the GPU-related resources allocated by this instance. Call this
  41084. * method whenever this instance is no longer used in your app.
  41085. */
  41086. dispose() {
  41087. this.children[ 0 ].geometry.dispose();
  41088. this.children[ 0 ].material.dispose();
  41089. }
  41090. /**
  41091. * Updates the helper to match the position and direction of the
  41092. * light being visualized.
  41093. */
  41094. update() {
  41095. const mesh = this.children[ 0 ];
  41096. if ( this.color !== undefined ) {
  41097. this.material.color.set( this.color );
  41098. } else {
  41099. const colors = mesh.geometry.getAttribute( 'color' );
  41100. _color1.copy( this.light.color );
  41101. _color2.copy( this.light.groundColor );
  41102. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41103. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41104. colors.setXYZ( i, color.r, color.g, color.b );
  41105. }
  41106. colors.needsUpdate = true;
  41107. }
  41108. this.light.updateWorldMatrix( true, false );
  41109. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41110. }
  41111. }
  41112. /**
  41113. * The helper is an object to define grids. Grids are two-dimensional
  41114. * arrays of lines.
  41115. *
  41116. * ```js
  41117. * const size = 10;
  41118. * const divisions = 10;
  41119. *
  41120. * const gridHelper = new THREE.GridHelper( size, divisions );
  41121. * scene.add( gridHelper );
  41122. * ```
  41123. *
  41124. * @augments LineSegments
  41125. */
  41126. class GridHelper extends LineSegments {
  41127. /**
  41128. * Constructs a new grid helper.
  41129. *
  41130. * @param {number} [size=10] - The size of the grid.
  41131. * @param {number} [divisions=10] - The number of divisions across the grid.
  41132. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41133. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41134. */
  41135. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41136. color1 = new Color( color1 );
  41137. color2 = new Color( color2 );
  41138. const center = divisions / 2;
  41139. const step = size / divisions;
  41140. const halfSize = size / 2;
  41141. const vertices = [], colors = [];
  41142. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41143. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41144. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41145. const color = i === center ? color1 : color2;
  41146. color.toArray( colors, j ); j += 3;
  41147. color.toArray( colors, j ); j += 3;
  41148. color.toArray( colors, j ); j += 3;
  41149. color.toArray( colors, j ); j += 3;
  41150. }
  41151. const geometry = new BufferGeometry();
  41152. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41153. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41154. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41155. super( geometry, material );
  41156. this.type = 'GridHelper';
  41157. }
  41158. /**
  41159. * Frees the GPU-related resources allocated by this instance. Call this
  41160. * method whenever this instance is no longer used in your app.
  41161. */
  41162. dispose() {
  41163. this.geometry.dispose();
  41164. this.material.dispose();
  41165. }
  41166. }
  41167. /**
  41168. * This helper is an object to define polar grids. Grids are
  41169. * two-dimensional arrays of lines.
  41170. *
  41171. * ```js
  41172. * const radius = 10;
  41173. * const sectors = 16;
  41174. * const rings = 8;
  41175. * const divisions = 64;
  41176. *
  41177. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41178. * scene.add( helper );
  41179. * ```
  41180. *
  41181. * @augments LineSegments
  41182. */
  41183. class PolarGridHelper extends LineSegments {
  41184. /**
  41185. * Constructs a new polar grid helper.
  41186. *
  41187. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41188. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41189. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41190. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41191. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41192. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41193. */
  41194. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41195. color1 = new Color( color1 );
  41196. color2 = new Color( color2 );
  41197. const vertices = [];
  41198. const colors = [];
  41199. // create the sectors
  41200. if ( sectors > 1 ) {
  41201. for ( let i = 0; i < sectors; i ++ ) {
  41202. const v = ( i / sectors ) * ( Math.PI * 2 );
  41203. const x = Math.sin( v ) * radius;
  41204. const z = Math.cos( v ) * radius;
  41205. vertices.push( 0, 0, 0 );
  41206. vertices.push( x, 0, z );
  41207. const color = ( i & 1 ) ? color1 : color2;
  41208. colors.push( color.r, color.g, color.b );
  41209. colors.push( color.r, color.g, color.b );
  41210. }
  41211. }
  41212. // create the rings
  41213. for ( let i = 0; i < rings; i ++ ) {
  41214. const color = ( i & 1 ) ? color1 : color2;
  41215. const r = radius - ( radius / rings * i );
  41216. for ( let j = 0; j < divisions; j ++ ) {
  41217. // first vertex
  41218. let v = ( j / divisions ) * ( Math.PI * 2 );
  41219. let x = Math.sin( v ) * r;
  41220. let z = Math.cos( v ) * r;
  41221. vertices.push( x, 0, z );
  41222. colors.push( color.r, color.g, color.b );
  41223. // second vertex
  41224. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41225. x = Math.sin( v ) * r;
  41226. z = Math.cos( v ) * r;
  41227. vertices.push( x, 0, z );
  41228. colors.push( color.r, color.g, color.b );
  41229. }
  41230. }
  41231. const geometry = new BufferGeometry();
  41232. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41233. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41234. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41235. super( geometry, material );
  41236. this.type = 'PolarGridHelper';
  41237. }
  41238. /**
  41239. * Frees the GPU-related resources allocated by this instance. Call this
  41240. * method whenever this instance is no longer used in your app.
  41241. */
  41242. dispose() {
  41243. this.geometry.dispose();
  41244. this.material.dispose();
  41245. }
  41246. }
  41247. const _v1 = /*@__PURE__*/ new Vector3();
  41248. const _v2 = /*@__PURE__*/ new Vector3();
  41249. const _v3 = /*@__PURE__*/ new Vector3();
  41250. /**
  41251. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41252. * effect on the scene. This consists of plane and a line representing the
  41253. * light's position and direction.
  41254. *
  41255. * ```js
  41256. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41257. * scene.add( light );
  41258. *
  41259. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41260. * scene.add( helper );
  41261. * ```
  41262. *
  41263. * @augments Object3D
  41264. */
  41265. class DirectionalLightHelper extends Object3D {
  41266. /**
  41267. * Constructs a new directional light helper.
  41268. *
  41269. * @param {DirectionalLight} light - The light to be visualized.
  41270. * @param {number} [size=1] - The dimensions of the plane.
  41271. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41272. * the color of the light.
  41273. */
  41274. constructor( light, size, color ) {
  41275. super();
  41276. /**
  41277. * The light being visualized.
  41278. *
  41279. * @type {DirectionalLight}
  41280. */
  41281. this.light = light;
  41282. this.matrix = light.matrixWorld;
  41283. this.matrixAutoUpdate = false;
  41284. /**
  41285. * The color parameter passed in the constructor.
  41286. * If not set, the helper will take the color of the light.
  41287. *
  41288. * @type {number|Color|string}
  41289. */
  41290. this.color = color;
  41291. this.type = 'DirectionalLightHelper';
  41292. if ( size === undefined ) size = 1;
  41293. let geometry = new BufferGeometry();
  41294. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41295. - size, size, 0,
  41296. size, size, 0,
  41297. size, - size, 0,
  41298. - size, - size, 0,
  41299. - size, size, 0
  41300. ], 3 ) );
  41301. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41302. /**
  41303. * Contains the line showing the location of the directional light.
  41304. *
  41305. * @type {Line}
  41306. */
  41307. this.lightPlane = new Line( geometry, material );
  41308. this.add( this.lightPlane );
  41309. geometry = new BufferGeometry();
  41310. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41311. /**
  41312. * Represents the target line of the directional light.
  41313. *
  41314. * @type {Line}
  41315. */
  41316. this.targetLine = new Line( geometry, material );
  41317. this.add( this.targetLine );
  41318. this.update();
  41319. }
  41320. /**
  41321. * Frees the GPU-related resources allocated by this instance. Call this
  41322. * method whenever this instance is no longer used in your app.
  41323. */
  41324. dispose() {
  41325. this.lightPlane.geometry.dispose();
  41326. this.lightPlane.material.dispose();
  41327. this.targetLine.geometry.dispose();
  41328. this.targetLine.material.dispose();
  41329. }
  41330. /**
  41331. * Updates the helper to match the position and direction of the
  41332. * light being visualized.
  41333. */
  41334. update() {
  41335. this.light.updateWorldMatrix( true, false );
  41336. this.light.target.updateWorldMatrix( true, false );
  41337. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41338. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41339. _v3.subVectors( _v2, _v1 );
  41340. this.lightPlane.lookAt( _v2 );
  41341. if ( this.color !== undefined ) {
  41342. this.lightPlane.material.color.set( this.color );
  41343. this.targetLine.material.color.set( this.color );
  41344. } else {
  41345. this.lightPlane.material.color.copy( this.light.color );
  41346. this.targetLine.material.color.copy( this.light.color );
  41347. }
  41348. this.targetLine.lookAt( _v2 );
  41349. this.targetLine.scale.z = _v3.length();
  41350. }
  41351. }
  41352. const _vector = /*@__PURE__*/ new Vector3();
  41353. const _camera = /*@__PURE__*/ new Camera();
  41354. /**
  41355. * This helps with visualizing what a camera contains in its frustum. It
  41356. * visualizes the frustum of a camera using a line segments.
  41357. *
  41358. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  41359. *
  41360. * `CameraHelper` must be a child of the scene.
  41361. *
  41362. * ```js
  41363. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41364. * const helper = new THREE.CameraHelper( camera );
  41365. * scene.add( helper );
  41366. * ```
  41367. *
  41368. * @augments LineSegments
  41369. */
  41370. class CameraHelper extends LineSegments {
  41371. /**
  41372. * Constructs a new arrow helper.
  41373. *
  41374. * @param {Camera} camera - The camera to visualize.
  41375. */
  41376. constructor( camera ) {
  41377. const geometry = new BufferGeometry();
  41378. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41379. const vertices = [];
  41380. const colors = [];
  41381. const pointMap = {};
  41382. // near
  41383. addLine( 'n1', 'n2' );
  41384. addLine( 'n2', 'n4' );
  41385. addLine( 'n4', 'n3' );
  41386. addLine( 'n3', 'n1' );
  41387. // far
  41388. addLine( 'f1', 'f2' );
  41389. addLine( 'f2', 'f4' );
  41390. addLine( 'f4', 'f3' );
  41391. addLine( 'f3', 'f1' );
  41392. // sides
  41393. addLine( 'n1', 'f1' );
  41394. addLine( 'n2', 'f2' );
  41395. addLine( 'n3', 'f3' );
  41396. addLine( 'n4', 'f4' );
  41397. // cone
  41398. addLine( 'p', 'n1' );
  41399. addLine( 'p', 'n2' );
  41400. addLine( 'p', 'n3' );
  41401. addLine( 'p', 'n4' );
  41402. // up
  41403. addLine( 'u1', 'u2' );
  41404. addLine( 'u2', 'u3' );
  41405. addLine( 'u3', 'u1' );
  41406. // target
  41407. addLine( 'c', 't' );
  41408. addLine( 'p', 'c' );
  41409. // cross
  41410. addLine( 'cn1', 'cn2' );
  41411. addLine( 'cn3', 'cn4' );
  41412. addLine( 'cf1', 'cf2' );
  41413. addLine( 'cf3', 'cf4' );
  41414. function addLine( a, b ) {
  41415. addPoint( a );
  41416. addPoint( b );
  41417. }
  41418. function addPoint( id ) {
  41419. vertices.push( 0, 0, 0 );
  41420. colors.push( 0, 0, 0 );
  41421. if ( pointMap[ id ] === undefined ) {
  41422. pointMap[ id ] = [];
  41423. }
  41424. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41425. }
  41426. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41427. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41428. super( geometry, material );
  41429. this.type = 'CameraHelper';
  41430. /**
  41431. * The camera being visualized.
  41432. *
  41433. * @type {Camera}
  41434. */
  41435. this.camera = camera;
  41436. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41437. this.matrix = camera.matrixWorld;
  41438. this.matrixAutoUpdate = false;
  41439. /**
  41440. * This contains the points used to visualize the camera.
  41441. *
  41442. * @type {Object<string,Array<number>>}
  41443. */
  41444. this.pointMap = pointMap;
  41445. this.update();
  41446. // colors
  41447. const colorFrustum = new Color( 0xffaa00 );
  41448. const colorCone = new Color( 0xff0000 );
  41449. const colorUp = new Color( 0x00aaff );
  41450. const colorTarget = new Color( 0xffffff );
  41451. const colorCross = new Color( 0x333333 );
  41452. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41453. }
  41454. /**
  41455. * Defines the colors of the helper.
  41456. *
  41457. * @param {Color} frustum - The frustum line color.
  41458. * @param {Color} cone - The cone line color.
  41459. * @param {Color} up - The up line color.
  41460. * @param {Color} target - The target line color.
  41461. * @param {Color} cross - The cross line color.
  41462. * @return {CameraHelper} A reference to this helper.
  41463. */
  41464. setColors( frustum, cone, up, target, cross ) {
  41465. const geometry = this.geometry;
  41466. const colorAttribute = geometry.getAttribute( 'color' );
  41467. // near
  41468. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41469. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41470. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41471. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41472. // far
  41473. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41474. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41475. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41476. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41477. // sides
  41478. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41479. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41480. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41481. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41482. // cone
  41483. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41484. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41485. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41486. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41487. // up
  41488. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41489. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41490. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41491. // target
  41492. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41493. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41494. // cross
  41495. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41496. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41497. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41498. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41499. colorAttribute.needsUpdate = true;
  41500. return this;
  41501. }
  41502. /**
  41503. * Updates the helper based on the projection matrix of the camera.
  41504. */
  41505. update() {
  41506. const geometry = this.geometry;
  41507. const pointMap = this.pointMap;
  41508. const w = 1, h = 1;
  41509. let nearZ, farZ;
  41510. // we need just camera projection matrix inverse
  41511. // world matrix must be identity
  41512. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41513. // Adjust z values based on coordinate system
  41514. if ( this.camera.reversedDepth === true ) {
  41515. nearZ = 1;
  41516. farZ = 0;
  41517. } else {
  41518. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41519. nearZ = -1;
  41520. farZ = 1;
  41521. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41522. nearZ = 0;
  41523. farZ = 1;
  41524. } else {
  41525. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41526. }
  41527. }
  41528. // center / target
  41529. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41530. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41531. // near
  41532. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41533. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41534. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41535. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41536. // far
  41537. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41538. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41539. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41540. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41541. // up
  41542. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41543. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41544. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41545. // cross
  41546. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41547. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41548. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41549. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41550. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41551. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41552. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41553. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41554. geometry.getAttribute( 'position' ).needsUpdate = true;
  41555. }
  41556. /**
  41557. * Frees the GPU-related resources allocated by this instance. Call this
  41558. * method whenever this instance is no longer used in your app.
  41559. */
  41560. dispose() {
  41561. this.geometry.dispose();
  41562. this.material.dispose();
  41563. }
  41564. }
  41565. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41566. _vector.set( x, y, z ).unproject( camera );
  41567. const points = pointMap[ point ];
  41568. if ( points !== undefined ) {
  41569. const position = geometry.getAttribute( 'position' );
  41570. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41571. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41572. }
  41573. }
  41574. }
  41575. const _box = /*@__PURE__*/ new Box3();
  41576. /**
  41577. * Helper object to graphically show the world-axis-aligned bounding box
  41578. * around an object. The actual bounding box is handled with {@link Box3},
  41579. * this is just a visual helper for debugging. It can be automatically
  41580. * resized with {@link BoxHelper#update} when the object it's created from
  41581. * is transformed. Note that the object must have a geometry for this to work,
  41582. * so it won't work with sprites.
  41583. *
  41584. * ```js
  41585. * const sphere = new THREE.SphereGeometry();
  41586. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41587. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41588. * scene.add( box );
  41589. * ```
  41590. *
  41591. * @augments LineSegments
  41592. */
  41593. class BoxHelper extends LineSegments {
  41594. /**
  41595. * Constructs a new box helper.
  41596. *
  41597. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41598. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41599. */
  41600. constructor( object, color = 0xffff00 ) {
  41601. 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 ] );
  41602. const positions = new Float32Array( 8 * 3 );
  41603. const geometry = new BufferGeometry();
  41604. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41605. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41606. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41607. /**
  41608. * The 3D object being visualized.
  41609. *
  41610. * @type {Object3D}
  41611. */
  41612. this.object = object;
  41613. this.type = 'BoxHelper';
  41614. this.matrixAutoUpdate = false;
  41615. this.update();
  41616. }
  41617. /**
  41618. * Updates the helper's geometry to match the dimensions of the object,
  41619. * including any children.
  41620. */
  41621. update() {
  41622. if ( this.object !== undefined ) {
  41623. _box.setFromObject( this.object );
  41624. }
  41625. if ( _box.isEmpty() ) return;
  41626. const min = _box.min;
  41627. const max = _box.max;
  41628. /*
  41629. 5____4
  41630. 1/___0/|
  41631. | 6__|_7
  41632. 2/___3/
  41633. 0: max.x, max.y, max.z
  41634. 1: min.x, max.y, max.z
  41635. 2: min.x, min.y, max.z
  41636. 3: max.x, min.y, max.z
  41637. 4: max.x, max.y, min.z
  41638. 5: min.x, max.y, min.z
  41639. 6: min.x, min.y, min.z
  41640. 7: max.x, min.y, min.z
  41641. */
  41642. const position = this.geometry.attributes.position;
  41643. const array = position.array;
  41644. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41645. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41646. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41647. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41648. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41649. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41650. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41651. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41652. position.needsUpdate = true;
  41653. this.geometry.computeBoundingSphere();
  41654. }
  41655. /**
  41656. * Updates the wireframe box for the passed object.
  41657. *
  41658. * @param {Object3D} object - The 3D object to create the helper for.
  41659. * @return {BoxHelper} A reference to this instance.
  41660. */
  41661. setFromObject( object ) {
  41662. this.object = object;
  41663. this.update();
  41664. return this;
  41665. }
  41666. copy( source, recursive ) {
  41667. super.copy( source, recursive );
  41668. this.object = source.object;
  41669. return this;
  41670. }
  41671. /**
  41672. * Frees the GPU-related resources allocated by this instance. Call this
  41673. * method whenever this instance is no longer used in your app.
  41674. */
  41675. dispose() {
  41676. this.geometry.dispose();
  41677. this.material.dispose();
  41678. }
  41679. }
  41680. /**
  41681. * A helper object to visualize an instance of {@link Box3}.
  41682. *
  41683. * ```js
  41684. * const box = new THREE.Box3();
  41685. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41686. *
  41687. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41688. * scene.add( helper )
  41689. * ```
  41690. *
  41691. * @augments LineSegments
  41692. */
  41693. class Box3Helper extends LineSegments {
  41694. /**
  41695. * Constructs a new box3 helper.
  41696. *
  41697. * @param {Box3} box - The box to visualize.
  41698. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41699. */
  41700. constructor( box, color = 0xffff00 ) {
  41701. 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 ] );
  41702. 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 ];
  41703. const geometry = new BufferGeometry();
  41704. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41705. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41706. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41707. /**
  41708. * The box being visualized.
  41709. *
  41710. * @type {Box3}
  41711. */
  41712. this.box = box;
  41713. this.type = 'Box3Helper';
  41714. this.geometry.computeBoundingSphere();
  41715. }
  41716. updateMatrixWorld( force ) {
  41717. const box = this.box;
  41718. if ( box.isEmpty() ) return;
  41719. box.getCenter( this.position );
  41720. box.getSize( this.scale );
  41721. this.scale.multiplyScalar( 0.5 );
  41722. super.updateMatrixWorld( force );
  41723. }
  41724. /**
  41725. * Frees the GPU-related resources allocated by this instance. Call this
  41726. * method whenever this instance is no longer used in your app.
  41727. */
  41728. dispose() {
  41729. this.geometry.dispose();
  41730. this.material.dispose();
  41731. }
  41732. }
  41733. /**
  41734. * A helper object to visualize an instance of {@link Plane}.
  41735. *
  41736. * ```js
  41737. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41738. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41739. * scene.add( helper );
  41740. * ```
  41741. *
  41742. * @augments Line
  41743. */
  41744. class PlaneHelper extends Line {
  41745. /**
  41746. * Constructs a new plane helper.
  41747. *
  41748. * @param {Plane} plane - The plane to be visualized.
  41749. * @param {number} [size=1] - The side length of plane helper.
  41750. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41751. */
  41752. constructor( plane, size = 1, hex = 0xffff00 ) {
  41753. const color = hex;
  41754. 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 ];
  41755. const geometry = new BufferGeometry();
  41756. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41757. geometry.computeBoundingSphere();
  41758. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41759. this.type = 'PlaneHelper';
  41760. /**
  41761. * The plane being visualized.
  41762. *
  41763. * @type {Plane}
  41764. */
  41765. this.plane = plane;
  41766. /**
  41767. * The side length of plane helper.
  41768. *
  41769. * @type {number}
  41770. * @default 1
  41771. */
  41772. this.size = size;
  41773. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41774. const geometry2 = new BufferGeometry();
  41775. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41776. geometry2.computeBoundingSphere();
  41777. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  41778. }
  41779. updateMatrixWorld( force ) {
  41780. this.position.set( 0, 0, 0 );
  41781. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  41782. this.lookAt( this.plane.normal );
  41783. this.translateZ( - this.plane.constant );
  41784. super.updateMatrixWorld( force );
  41785. }
  41786. /**
  41787. * Updates the helper to match the position and direction of the
  41788. * light being visualized.
  41789. */
  41790. dispose() {
  41791. this.geometry.dispose();
  41792. this.material.dispose();
  41793. this.children[ 0 ].geometry.dispose();
  41794. this.children[ 0 ].material.dispose();
  41795. }
  41796. }
  41797. const _axis = /*@__PURE__*/ new Vector3();
  41798. let _lineGeometry, _coneGeometry;
  41799. /**
  41800. * An 3D arrow object for visualizing directions.
  41801. *
  41802. * ```js
  41803. * const dir = new THREE.Vector3( 1, 2, 0 );
  41804. *
  41805. * //normalize the direction vector (convert to vector of length 1)
  41806. * dir.normalize();
  41807. *
  41808. * const origin = new THREE.Vector3( 0, 0, 0 );
  41809. * const length = 1;
  41810. * const hex = 0xffff00;
  41811. *
  41812. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  41813. * scene.add( arrowHelper );
  41814. * ```
  41815. *
  41816. * @augments Object3D
  41817. */
  41818. class ArrowHelper extends Object3D {
  41819. /**
  41820. * Constructs a new arrow helper.
  41821. *
  41822. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  41823. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  41824. * @param {number} [length=1] - Length of the arrow in world units.
  41825. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  41826. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41827. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41828. */
  41829. 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 ) {
  41830. super();
  41831. this.type = 'ArrowHelper';
  41832. if ( _lineGeometry === undefined ) {
  41833. _lineGeometry = new BufferGeometry();
  41834. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  41835. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  41836. _coneGeometry.translate( 0, -0.5, 0 );
  41837. }
  41838. this.position.copy( origin );
  41839. /**
  41840. * The line part of the arrow helper.
  41841. *
  41842. * @type {Line}
  41843. */
  41844. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41845. this.line.matrixAutoUpdate = false;
  41846. this.add( this.line );
  41847. /**
  41848. * The cone part of the arrow helper.
  41849. *
  41850. * @type {Mesh}
  41851. */
  41852. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  41853. this.cone.matrixAutoUpdate = false;
  41854. this.add( this.cone );
  41855. this.setDirection( dir );
  41856. this.setLength( length, headLength, headWidth );
  41857. }
  41858. /**
  41859. * Sets the direction of the helper.
  41860. *
  41861. * @param {Vector3} dir - The normalized direction vector.
  41862. */
  41863. setDirection( dir ) {
  41864. // dir is assumed to be normalized
  41865. if ( dir.y > 0.99999 ) {
  41866. this.quaternion.set( 0, 0, 0, 1 );
  41867. } else if ( dir.y < -0.99999 ) {
  41868. this.quaternion.set( 1, 0, 0, 0 );
  41869. } else {
  41870. _axis.set( dir.z, 0, - dir.x ).normalize();
  41871. const radians = Math.acos( dir.y );
  41872. this.quaternion.setFromAxisAngle( _axis, radians );
  41873. }
  41874. }
  41875. /**
  41876. * Sets the length of the helper.
  41877. *
  41878. * @param {number} length - Length of the arrow in world units.
  41879. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41880. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41881. */
  41882. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  41883. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  41884. this.line.updateMatrix();
  41885. this.cone.scale.set( headWidth, headLength, headWidth );
  41886. this.cone.position.y = length;
  41887. this.cone.updateMatrix();
  41888. }
  41889. /**
  41890. * Sets the color of the helper.
  41891. *
  41892. * @param {number|Color|string} color - The color to set.
  41893. */
  41894. setColor( color ) {
  41895. this.line.material.color.set( color );
  41896. this.cone.material.color.set( color );
  41897. }
  41898. copy( source ) {
  41899. super.copy( source, false );
  41900. this.line.copy( source.line );
  41901. this.cone.copy( source.cone );
  41902. return this;
  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.line.geometry.dispose();
  41910. this.line.material.dispose();
  41911. this.cone.geometry.dispose();
  41912. this.cone.material.dispose();
  41913. }
  41914. }
  41915. /**
  41916. * An axis object to visualize the 3 axes in a simple way.
  41917. * The X axis is red. The Y axis is green. The Z axis is blue.
  41918. *
  41919. * ```js
  41920. * const axesHelper = new THREE.AxesHelper( 5 );
  41921. * scene.add( axesHelper );
  41922. * ```
  41923. *
  41924. * @augments LineSegments
  41925. */
  41926. class AxesHelper extends LineSegments {
  41927. /**
  41928. * Constructs a new axes helper.
  41929. *
  41930. * @param {number} [size=1] - Size of the lines representing the axes.
  41931. */
  41932. constructor( size = 1 ) {
  41933. const vertices = [
  41934. 0, 0, 0, size, 0, 0,
  41935. 0, 0, 0, 0, size, 0,
  41936. 0, 0, 0, 0, 0, size
  41937. ];
  41938. const colors = [
  41939. 1, 0, 0, 1, 0.6, 0,
  41940. 0, 1, 0, 0.6, 1, 0,
  41941. 0, 0, 1, 0, 0.6, 1
  41942. ];
  41943. const geometry = new BufferGeometry();
  41944. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41945. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41946. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41947. super( geometry, material );
  41948. this.type = 'AxesHelper';
  41949. }
  41950. /**
  41951. * Defines the colors of the axes helper.
  41952. *
  41953. * @param {number|Color|string} xAxisColor - The color for the x axis.
  41954. * @param {number|Color|string} yAxisColor - The color for the y axis.
  41955. * @param {number|Color|string} zAxisColor - The color for the z axis.
  41956. * @return {AxesHelper} A reference to this axes helper.
  41957. */
  41958. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  41959. const color = new Color();
  41960. const array = this.geometry.attributes.color.array;
  41961. color.set( xAxisColor );
  41962. color.toArray( array, 0 );
  41963. color.toArray( array, 3 );
  41964. color.set( yAxisColor );
  41965. color.toArray( array, 6 );
  41966. color.toArray( array, 9 );
  41967. color.set( zAxisColor );
  41968. color.toArray( array, 12 );
  41969. color.toArray( array, 15 );
  41970. this.geometry.attributes.color.needsUpdate = true;
  41971. return this;
  41972. }
  41973. /**
  41974. * Frees the GPU-related resources allocated by this instance. Call this
  41975. * method whenever this instance is no longer used in your app.
  41976. */
  41977. dispose() {
  41978. this.geometry.dispose();
  41979. this.material.dispose();
  41980. }
  41981. }
  41982. /**
  41983. * This class is used to convert a series of paths to an array of
  41984. * shapes. It is specifically used in context of fonts and SVG.
  41985. */
  41986. class ShapePath {
  41987. /**
  41988. * Constructs a new shape path.
  41989. */
  41990. constructor() {
  41991. this.type = 'ShapePath';
  41992. /**
  41993. * The color of the shape.
  41994. *
  41995. * @type {Color}
  41996. */
  41997. this.color = new Color();
  41998. /**
  41999. * The paths that have been generated for this shape.
  42000. *
  42001. * @type {Array<Path>}
  42002. * @default null
  42003. */
  42004. this.subPaths = [];
  42005. /**
  42006. * The current path that is being generated.
  42007. *
  42008. * @type {?Path}
  42009. * @default null
  42010. */
  42011. this.currentPath = null;
  42012. }
  42013. /**
  42014. * Creates a new path and moves it current point to the given one.
  42015. *
  42016. * @param {number} x - The x coordinate.
  42017. * @param {number} y - The y coordinate.
  42018. * @return {ShapePath} A reference to this shape path.
  42019. */
  42020. moveTo( x, y ) {
  42021. this.currentPath = new Path();
  42022. this.subPaths.push( this.currentPath );
  42023. this.currentPath.moveTo( x, y );
  42024. return this;
  42025. }
  42026. /**
  42027. * Adds an instance of {@link LineCurve} to the path by connecting
  42028. * the current point with the given one.
  42029. *
  42030. * @param {number} x - The x coordinate of the end point.
  42031. * @param {number} y - The y coordinate of the end point.
  42032. * @return {ShapePath} A reference to this shape path.
  42033. */
  42034. lineTo( x, y ) {
  42035. this.currentPath.lineTo( x, y );
  42036. return this;
  42037. }
  42038. /**
  42039. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42040. * the current point with the given one.
  42041. *
  42042. * @param {number} aCPx - The x coordinate of the control point.
  42043. * @param {number} aCPy - The y coordinate of the control point.
  42044. * @param {number} aX - The x coordinate of the end point.
  42045. * @param {number} aY - The y coordinate of the end point.
  42046. * @return {ShapePath} A reference to this shape path.
  42047. */
  42048. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42049. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42050. return this;
  42051. }
  42052. /**
  42053. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42054. * the current point with the given one.
  42055. *
  42056. * @param {number} aCP1x - The x coordinate of the first control point.
  42057. * @param {number} aCP1y - The y coordinate of the first control point.
  42058. * @param {number} aCP2x - The x coordinate of the second control point.
  42059. * @param {number} aCP2y - The y coordinate of the second control point.
  42060. * @param {number} aX - The x coordinate of the end point.
  42061. * @param {number} aY - The y coordinate of the end point.
  42062. * @return {ShapePath} A reference to this shape path.
  42063. */
  42064. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42065. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42066. return this;
  42067. }
  42068. /**
  42069. * Adds an instance of {@link SplineCurve} to the path by connecting
  42070. * the current point with the given list of points.
  42071. *
  42072. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42073. * @return {ShapePath} A reference to this shape path.
  42074. */
  42075. splineThru( pts ) {
  42076. this.currentPath.splineThru( pts );
  42077. return this;
  42078. }
  42079. /**
  42080. * Converts the paths into an array of shapes.
  42081. *
  42082. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42083. * If this flag is set to `true`, then those are flipped.
  42084. * @return {Array<Shape>} An array of shapes.
  42085. */
  42086. toShapes( isCCW ) {
  42087. function toShapesNoHoles( inSubpaths ) {
  42088. const shapes = [];
  42089. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42090. const tmpPath = inSubpaths[ i ];
  42091. const tmpShape = new Shape();
  42092. tmpShape.curves = tmpPath.curves;
  42093. shapes.push( tmpShape );
  42094. }
  42095. return shapes;
  42096. }
  42097. function isPointInsidePolygon( inPt, inPolygon ) {
  42098. const polyLen = inPolygon.length;
  42099. // inPt on polygon contour => immediate success or
  42100. // toggling of inside/outside at every single! intersection point of an edge
  42101. // with the horizontal line through inPt, left of inPt
  42102. // not counting lowerY endpoints of edges and whole edges on that line
  42103. let inside = false;
  42104. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42105. let edgeLowPt = inPolygon[ p ];
  42106. let edgeHighPt = inPolygon[ q ];
  42107. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42108. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42109. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42110. // not parallel
  42111. if ( edgeDy < 0 ) {
  42112. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42113. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42114. }
  42115. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42116. if ( inPt.y === edgeLowPt.y ) {
  42117. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42118. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42119. } else {
  42120. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42121. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42122. if ( perpEdge < 0 ) continue;
  42123. inside = ! inside; // true intersection left of inPt
  42124. }
  42125. } else {
  42126. // parallel or collinear
  42127. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42128. // edge lies on the same horizontal line as inPt
  42129. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42130. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42131. // continue;
  42132. }
  42133. }
  42134. return inside;
  42135. }
  42136. const isClockWise = ShapeUtils.isClockWise;
  42137. const subPaths = this.subPaths;
  42138. if ( subPaths.length === 0 ) return [];
  42139. let solid, tmpPath, tmpShape;
  42140. const shapes = [];
  42141. if ( subPaths.length === 1 ) {
  42142. tmpPath = subPaths[ 0 ];
  42143. tmpShape = new Shape();
  42144. tmpShape.curves = tmpPath.curves;
  42145. shapes.push( tmpShape );
  42146. return shapes;
  42147. }
  42148. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42149. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42150. // console.log("Holes first", holesFirst);
  42151. const betterShapeHoles = [];
  42152. const newShapes = [];
  42153. let newShapeHoles = [];
  42154. let mainIdx = 0;
  42155. let tmpPoints;
  42156. newShapes[ mainIdx ] = undefined;
  42157. newShapeHoles[ mainIdx ] = [];
  42158. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42159. tmpPath = subPaths[ i ];
  42160. tmpPoints = tmpPath.getPoints();
  42161. solid = isClockWise( tmpPoints );
  42162. solid = isCCW ? ! solid : solid;
  42163. if ( solid ) {
  42164. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42165. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42166. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42167. if ( holesFirst ) mainIdx ++;
  42168. newShapeHoles[ mainIdx ] = [];
  42169. //console.log('cw', i);
  42170. } else {
  42171. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42172. //console.log('ccw', i);
  42173. }
  42174. }
  42175. // only Holes? -> probably all Shapes with wrong orientation
  42176. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42177. if ( newShapes.length > 1 ) {
  42178. let ambiguous = false;
  42179. let toChange = 0;
  42180. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42181. betterShapeHoles[ sIdx ] = [];
  42182. }
  42183. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42184. const sho = newShapeHoles[ sIdx ];
  42185. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42186. const ho = sho[ hIdx ];
  42187. let hole_unassigned = true;
  42188. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42189. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42190. if ( sIdx !== s2Idx ) toChange ++;
  42191. if ( hole_unassigned ) {
  42192. hole_unassigned = false;
  42193. betterShapeHoles[ s2Idx ].push( ho );
  42194. } else {
  42195. ambiguous = true;
  42196. }
  42197. }
  42198. }
  42199. if ( hole_unassigned ) {
  42200. betterShapeHoles[ sIdx ].push( ho );
  42201. }
  42202. }
  42203. }
  42204. if ( toChange > 0 && ambiguous === false ) {
  42205. newShapeHoles = betterShapeHoles;
  42206. }
  42207. }
  42208. let tmpHoles;
  42209. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42210. tmpShape = newShapes[ i ].s;
  42211. shapes.push( tmpShape );
  42212. tmpHoles = newShapeHoles[ i ];
  42213. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42214. tmpShape.holes.push( tmpHoles[ j ].h );
  42215. }
  42216. }
  42217. //console.log("shape", shapes);
  42218. return shapes;
  42219. }
  42220. }
  42221. /**
  42222. * Abstract base class for controls.
  42223. *
  42224. * @abstract
  42225. * @augments EventDispatcher
  42226. */
  42227. class Controls extends EventDispatcher {
  42228. /**
  42229. * Constructs a new controls instance.
  42230. *
  42231. * @param {Object3D} object - The object that is managed by the controls.
  42232. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  42233. */
  42234. constructor( object, domElement = null ) {
  42235. super();
  42236. /**
  42237. * The object that is managed by the controls.
  42238. *
  42239. * @type {Object3D}
  42240. */
  42241. this.object = object;
  42242. /**
  42243. * The HTML element used for event listeners.
  42244. *
  42245. * @type {?HTMLDOMElement}
  42246. * @default null
  42247. */
  42248. this.domElement = domElement;
  42249. /**
  42250. * Whether the controls responds to user input or not.
  42251. *
  42252. * @type {boolean}
  42253. * @default true
  42254. */
  42255. this.enabled = true;
  42256. /**
  42257. * The internal state of the controls.
  42258. *
  42259. * @type {number}
  42260. * @default -1
  42261. */
  42262. this.state = -1;
  42263. /**
  42264. * This object defines the keyboard input of the controls.
  42265. *
  42266. * @type {Object}
  42267. */
  42268. this.keys = {};
  42269. /**
  42270. * This object defines what type of actions are assigned to the available mouse buttons.
  42271. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42272. *
  42273. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42274. */
  42275. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42276. /**
  42277. * This object defines what type of actions are assigned to what kind of touch interaction.
  42278. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42279. *
  42280. * @type {{ONE: ?number, TWO: ?number}}
  42281. */
  42282. this.touches = { ONE: null, TWO: null };
  42283. }
  42284. /**
  42285. * Connects the controls to the DOM. This method has so called "side effects" since
  42286. * it adds the module's event listeners to the DOM.
  42287. *
  42288. * @param {HTMLDOMElement} element - The DOM element to connect to.
  42289. */
  42290. connect( element ) {
  42291. if ( element === undefined ) {
  42292. console.warn( 'THREE.Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42293. return;
  42294. }
  42295. if ( this.domElement !== null ) this.disconnect();
  42296. this.domElement = element;
  42297. }
  42298. /**
  42299. * Disconnects the controls from the DOM.
  42300. */
  42301. disconnect() {}
  42302. /**
  42303. * Call this method if you no longer want use to the controls. It frees all internal
  42304. * resources and removes all event listeners.
  42305. */
  42306. dispose() {}
  42307. /**
  42308. * Controls should implement this method if they have to update their internal state
  42309. * per simulation step.
  42310. *
  42311. * @param {number} [delta] - The time delta in seconds.
  42312. */
  42313. update( /* delta */ ) {}
  42314. }
  42315. /**
  42316. * Scales the texture as large as possible within its surface without cropping
  42317. * or stretching the texture. The method preserves the original aspect ratio of
  42318. * the texture. Akin to CSS `object-fit: contain`
  42319. *
  42320. * @param {Texture} texture - The texture.
  42321. * @param {number} aspect - The texture's aspect ratio.
  42322. * @return {Texture} The updated texture.
  42323. */
  42324. function contain( texture, aspect ) {
  42325. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42326. if ( imageAspect > aspect ) {
  42327. texture.repeat.x = 1;
  42328. texture.repeat.y = imageAspect / aspect;
  42329. texture.offset.x = 0;
  42330. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42331. } else {
  42332. texture.repeat.x = aspect / imageAspect;
  42333. texture.repeat.y = 1;
  42334. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42335. texture.offset.y = 0;
  42336. }
  42337. return texture;
  42338. }
  42339. /**
  42340. * Scales the texture to the smallest possible size to fill the surface, leaving
  42341. * no empty space. The method preserves the original aspect ratio of the texture.
  42342. * Akin to CSS `object-fit: cover`.
  42343. *
  42344. * @param {Texture} texture - The texture.
  42345. * @param {number} aspect - The texture's aspect ratio.
  42346. * @return {Texture} The updated texture.
  42347. */
  42348. function cover( texture, aspect ) {
  42349. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42350. if ( imageAspect > aspect ) {
  42351. texture.repeat.x = aspect / imageAspect;
  42352. texture.repeat.y = 1;
  42353. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42354. texture.offset.y = 0;
  42355. } else {
  42356. texture.repeat.x = 1;
  42357. texture.repeat.y = imageAspect / aspect;
  42358. texture.offset.x = 0;
  42359. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42360. }
  42361. return texture;
  42362. }
  42363. /**
  42364. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42365. *
  42366. * @param {Texture} texture - The texture.
  42367. * @return {Texture} The updated texture.
  42368. */
  42369. function fill( texture ) {
  42370. texture.repeat.x = 1;
  42371. texture.repeat.y = 1;
  42372. texture.offset.x = 0;
  42373. texture.offset.y = 0;
  42374. return texture;
  42375. }
  42376. /**
  42377. * Determines how many bytes must be used to represent the texture.
  42378. *
  42379. * @param {number} width - The width of the texture.
  42380. * @param {number} height - The height of the texture.
  42381. * @param {number} format - The texture's format.
  42382. * @param {number} type - The texture's type.
  42383. * @return {number} The byte length.
  42384. */
  42385. function getByteLength( width, height, format, type ) {
  42386. const typeByteLength = getTextureTypeByteLength( type );
  42387. switch ( format ) {
  42388. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42389. case AlphaFormat:
  42390. return width * height;
  42391. case RedFormat:
  42392. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42393. case RedIntegerFormat:
  42394. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42395. case RGFormat:
  42396. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42397. case RGIntegerFormat:
  42398. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42399. case RGBFormat:
  42400. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42401. case RGBAFormat:
  42402. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42403. case RGBAIntegerFormat:
  42404. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42405. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42406. case RGB_S3TC_DXT1_Format:
  42407. case RGBA_S3TC_DXT1_Format:
  42408. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42409. case RGBA_S3TC_DXT3_Format:
  42410. case RGBA_S3TC_DXT5_Format:
  42411. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42412. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42413. case RGB_PVRTC_2BPPV1_Format:
  42414. case RGBA_PVRTC_2BPPV1_Format:
  42415. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42416. case RGB_PVRTC_4BPPV1_Format:
  42417. case RGBA_PVRTC_4BPPV1_Format:
  42418. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42419. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42420. case RGB_ETC1_Format:
  42421. case RGB_ETC2_Format:
  42422. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42423. case RGBA_ETC2_EAC_Format:
  42424. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42425. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42426. case RGBA_ASTC_4x4_Format:
  42427. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42428. case RGBA_ASTC_5x4_Format:
  42429. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42430. case RGBA_ASTC_5x5_Format:
  42431. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42432. case RGBA_ASTC_6x5_Format:
  42433. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42434. case RGBA_ASTC_6x6_Format:
  42435. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42436. case RGBA_ASTC_8x5_Format:
  42437. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42438. case RGBA_ASTC_8x6_Format:
  42439. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42440. case RGBA_ASTC_8x8_Format:
  42441. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42442. case RGBA_ASTC_10x5_Format:
  42443. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42444. case RGBA_ASTC_10x6_Format:
  42445. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42446. case RGBA_ASTC_10x8_Format:
  42447. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42448. case RGBA_ASTC_10x10_Format:
  42449. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42450. case RGBA_ASTC_12x10_Format:
  42451. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42452. case RGBA_ASTC_12x12_Format:
  42453. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42454. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42455. case RGBA_BPTC_Format:
  42456. case RGB_BPTC_SIGNED_Format:
  42457. case RGB_BPTC_UNSIGNED_Format:
  42458. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42459. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42460. case RED_RGTC1_Format:
  42461. case SIGNED_RED_RGTC1_Format:
  42462. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42463. case RED_GREEN_RGTC2_Format:
  42464. case SIGNED_RED_GREEN_RGTC2_Format:
  42465. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42466. }
  42467. throw new Error(
  42468. `Unable to determine texture byte length for ${format} format.`,
  42469. );
  42470. }
  42471. function getTextureTypeByteLength( type ) {
  42472. switch ( type ) {
  42473. case UnsignedByteType:
  42474. case ByteType:
  42475. return { byteLength: 1, components: 1 };
  42476. case UnsignedShortType:
  42477. case ShortType:
  42478. case HalfFloatType:
  42479. return { byteLength: 2, components: 1 };
  42480. case UnsignedShort4444Type:
  42481. case UnsignedShort5551Type:
  42482. return { byteLength: 2, components: 4 };
  42483. case UnsignedIntType:
  42484. case IntType:
  42485. case FloatType:
  42486. return { byteLength: 4, components: 1 };
  42487. case UnsignedInt5999Type:
  42488. case UnsignedInt101111Type:
  42489. return { byteLength: 4, components: 3 };
  42490. }
  42491. throw new Error( `Unknown texture type ${type}.` );
  42492. }
  42493. /**
  42494. * A class containing utility functions for textures.
  42495. *
  42496. * @hideconstructor
  42497. */
  42498. class TextureUtils {
  42499. /**
  42500. * Scales the texture as large as possible within its surface without cropping
  42501. * or stretching the texture. The method preserves the original aspect ratio of
  42502. * the texture. Akin to CSS `object-fit: contain`
  42503. *
  42504. * @param {Texture} texture - The texture.
  42505. * @param {number} aspect - The texture's aspect ratio.
  42506. * @return {Texture} The updated texture.
  42507. */
  42508. static contain( texture, aspect ) {
  42509. return contain( texture, aspect );
  42510. }
  42511. /**
  42512. * Scales the texture to the smallest possible size to fill the surface, leaving
  42513. * no empty space. The method preserves the original aspect ratio of the texture.
  42514. * Akin to CSS `object-fit: cover`.
  42515. *
  42516. * @param {Texture} texture - The texture.
  42517. * @param {number} aspect - The texture's aspect ratio.
  42518. * @return {Texture} The updated texture.
  42519. */
  42520. static cover( texture, aspect ) {
  42521. return cover( texture, aspect );
  42522. }
  42523. /**
  42524. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42525. *
  42526. * @param {Texture} texture - The texture.
  42527. * @return {Texture} The updated texture.
  42528. */
  42529. static fill( texture ) {
  42530. return fill( texture );
  42531. }
  42532. /**
  42533. * Determines how many bytes must be used to represent the texture.
  42534. *
  42535. * @param {number} width - The width of the texture.
  42536. * @param {number} height - The height of the texture.
  42537. * @param {number} format - The texture's format.
  42538. * @param {number} type - The texture's type.
  42539. * @return {number} The byte length.
  42540. */
  42541. static getByteLength( width, height, format, type ) {
  42542. return getByteLength( width, height, format, type );
  42543. }
  42544. }
  42545. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42546. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42547. revision: REVISION,
  42548. } } ) );
  42549. }
  42550. if ( typeof window !== 'undefined' ) {
  42551. if ( window.__THREE__ ) {
  42552. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42553. } else {
  42554. window.__THREE__ = REVISION;
  42555. }
  42556. }
  42557. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExternalTexture, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, FrustumArray, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Material, 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, NoToneMapping, NormalAnimationBlendMode, NormalBlending, 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, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, 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_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_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, getByteLength, getUnlitUniformColorSpace, mergeUniforms, probeAsync, warnOnce };
粤ICP备19079148号